Skip to content

JavaScript promise then

  • by

In JavaScript, a Promise is an object that represents the eventual completion or failure of an asynchronous operation and allows you to handle the result using the then method. The then method is used to attach callbacks to a Promise object, which will be executed when the promise is resolved or rejected.

The syntax for using then with a Promise is as follows:

promise.then(onResolve, onReject);
  • onResolve is a function that will be executed when the promise is resolved.
  • onReject is a function that will be executed when the promise is rejected.

JavaScript promises then example

Simple example code that demonstrates the usage of then with a Promise:

function asyncOperation() {
  return new Promise(function(resolve, reject) {
    // Simulating an asynchronous operation
    setTimeout(function() {
      const result = Math.random();
      if (result < 0.5) {
        resolve(result); // Resolve the promise with the result
      } else {
        reject("Operation failed"); // Reject the promise with an error message
      }
    }, 1000);
  });
}

asyncOperation()
  .then(function(result) {
    console.log("Operation succeeded with result: " + result);
  })
  .catch(function(error) {
    console.log("Operation failed with error: " + error);
  });

Output:

JavaScript promise then

Note: the then method returns a new Promise object, which allows the chaining of multiple then and catch calls together to handle the asynchronous flow in a more readable and manageable way.

Do comment if you have any doubts or suggestions on this Js Async topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *