JavaScript Promise Object

A Promise object represents the completion or failure of an asynchronous operation and its result.

A Promise can have the following 3 states:

pending Initial state
rejected Operation failed
fulfilled Operation completed

Instance

// Create a Promise object
let myPromise = new Promise(function(myResolve, myReject) {
  let result = true;
// Place potentially time-consuming code here
  if (result == true) {
    myResolve("OK");
  }
    myReject("Error");
  }
});
// Display the result using then()
myPromise.then(x => myDisplay(x), x => myDisplay(x));

Try it yourself

JavaScript Promise Methods and Properties

Name Description
Promise.all()

Returns a single Promise from a set of Promises.

When all Promises have been completed.

Promise.allSettled()

Returns a single Promise from a set of Promises.

When all Promises have been fulfilled.

Promise.any()

Returns a single Promise from a set of Promises.

When any Promise is fulfilled.

Promise.race()

Returns a single Promise from a set of Promises.

When the faster Promise is fulfilled.

Promise.reject() Returns a rejected Promise object with a value.
Promise.resolve() Returns a fulfilled Promise object with a value.
catch() Provide a function to be called when a Promise is rejected.
finally() Provide a function to be called when a Promise is fulfilled or rejected.
then() Provide two functions to be called when a Promise is fulfilled or rejected.

See also:

Tutorial:JavaScript Promise