Promises in JavaScript¶
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.
Creating a Promise¶
You can create a Promise using the new Promise() syntax. The Promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
Consuming a Promise¶
The then() method is used to schedule code to be run if the Promise is fulfilled or rejected. The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Promise States¶
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.fulfilled: meaning that the operation was completed successfully.rejected: meaning that the operation failed.
The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise’s then method are called.
Chaining Promises¶
The then() method returns a Promise, which allows for method chaining. If the function passed as handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain.
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
});
promise.then(function(result) {
console.log(result); // 1
return result * 2;
}).then(function(result) {
console.log(result); // 2
return result * 2;
}).then(function(result) {
console.log(result); // 4
return result * 2;
});
Error Handling¶
The catch() method returns a Promise and deals with rejected cases only2. It behaves the same as calling Promise.prototype.then(undefined, onRejected)2. In fact, catch(onRejected) is internally implemented as then(undefined, onRejected)2.
myPromise.catch(
function(reason) {
console.log('Handle rejected Promise ('+reason+') here.');
});