The Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
To learn about the way promises work and how you can use them, we advise you to read Using promises first.
Description
A Promise
is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise
is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation completed successfully.
- rejected: meaning that the operation failed.
A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then
method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
As the
and Promise.prototype.then()
methods return promises, they can be chained.Promise.prototype.catch()
Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression
to create the lazily-evaluated expression, and f()
to evaluate.
Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled or βlocked inβ to match the state of another promise. States and fates contains more details about promise terminology.
Chained Promises
The methods promise.then()
, promise.catch()
, and promise.finally()
are used to associate further action with a promise that becomes settled. These methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this:
-
const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA,handleRejectedA) .then(handleFulfilledB,handleRejectedB) .then(handleFulfilledC,handleRejectedC); // or, perhaps better ... const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA) .then(handleFulfilledB) .then(handleFulfilledC) .catch(handleRejectedAny);
Handling a rejected promise too early has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. (See throw -999
in the example, below, for a technique to handle the consequences.) On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement.
The signatures of these two functions are simple, they accept a single parameter of any type. These functions are written by you, the programmer. The termination condition of these functions determines the "settled" state of the next promise in the chain. Any termination other than a throw
creates a "resolved" state, while terminating with a throw
creates a "rejected" state.
handleFulfilled(value) { /*...*/; return nextValue; } handleRejection(reason) { /*...*/; throw nextReason; } handleRejection(reason) { /*...*/; return nextValue; }
The returned nextValue
can be another promise object, in which case the promise gets dynamically inserted into the chain.
When a .then()
lacks the appropriate function that return a Promise object, processing simply continues to the next link of the chain. Therefore, a chain can safely omit every handleRejection
until the final .catch()
. Similarly, .catch()
is really just a .then()
without a slot for handleFulfilled
.
The promises of a chain are nested like Russian dolls, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop.
(promise D, (promise C, (promise B, (promise A) ) ) )
When a nextValue
is a promise, the effect is a dynamic replacement. The return
causes a promise to be popped, but the nextValue
promise is pushed into its place. For the nesting shown above, suppose the .then()
associated with "promise B" returns a nextValue
of "promise X". The resulting nesting would look like this:
(promise D, (promise C, (promise X) ) )
A promise can participate in more than one nesting. For the following code, the transiton of promiseA
into a "settled" state will cause both instances of .then()
to be invoked.
const promiseA = new Promise(myExecutorFunc); const promiseB = promiseA.then(handleFulfilled1, handleRejected1); const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
An action can be assigned to an already "settled" promise. In that case the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed to be asynchronous. Therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. The effect is much like that of setTimeout(action,10)
.
const promiseA = new Promise( (resolutionFunc,rejectionFunc) => { resolutionFunc(777); }); // At this point, "promiseA" is already settled. promiseA.then( (val) => console.log("asynchronous logging has val:",val) ); console.log("immediate logging"); // produces output in this order: // immediate logging // asynchronous logging has val: 777
Constructor
Promise()
- Creates a new
Promise
object. The constructor is primarily used to wrap functions that do not already support promises.
Static methods
Promise.all(iterable)
- Wait for all promises to be resolved, or for any to be rejected.
- If the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises ,in the same order as defined in the iterable of multiple promises.
- If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected.
Promise.allSettled(iterable)
- Wait until all promises have settled (each may resolve or reject).
- Returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.
Promise.any(iterable)
- Takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfils, returns a single promise that resolves with the value from that promise.
Promise.race(iterable)
- Wait until any of the promises is resolved or rejected.
- If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved.
- If it rejects, it is rejected with the reason from the first promise that was rejected.
Promise.reject(reason)
- Returns a new
Promise
object that is rejected with the given reason. Promise.resolve(value)
- Returns a new
Promise
object that is resolved with the given value. If the value is a thenable (i.e. has athen
method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. - Generally, if you don't know if a value is a promise or not,
Promise.resolve(value)
it instead and work with the return value as a promise.
Instance methods
Promise.prototype.catch()
- Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
Promise.prototype.then()
- Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler
onFulfilled
oronRejected
is not a function). Promise.prototype.finally()
- Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.
Examples
Basic Example
let myFirstPromise = new Promise((resolve, reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR or an HTML5 API. setTimeout( function() { resolve("Success!") // Yay! Everything went well! }, 250) }) myFirstPromise.then((successMessage) => { // successMessage is whatever we passed in the resolve(...) function above. // It doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("Yay! " + successMessage) });
Example with diverse situations
This example shows diverse techniques for using Promise capabilities, and diverse situations that can occur. To understand this, start by scrolling to the bottom of the code block, and examine the promise chain. Upon provision of an initial promise, a chain of promises can follow. The chain is composed of .then()
calls, and typically (but not necessarily) has a single .catch()
at the end, optionally followed by .finally()
. In this example, the promise chain is initiated by a custom written new Promise()
construct; but in actual practice, promise chains more typically start with an API function (written by someone else) that returns a promise.
The example function tetheredGetNumber()
shows that a promise generator will utilize reject()
while setting up an asynchronous call, or within the call-back, or both. The function promiseGetWord()
illustrates how an API function might generate and return a promise in a self contained manner.
Note that function troubleWithGetNumber()
ends with a throw()
. That is forced because an ES6 promise chain goes through all the .then()
promises, even after an error, and without the "throw()", the error would seem "fixed". This is a hassle, and for this reason, it is common to omit rejectionFunc
throughout the chain of .then()
promises, and just have a single rejectionFunc
in the final catch()
. The alternative is to throw a special value (in this case "-999", but a custom Error type would be more appropriate).
This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the threshold
values.
"use strict"; // To experiment with error handling, "threshold" values cause errors randomly const THRESHOLD_A = 8; // can use zero 0 to guarantee error function tetheredGetNumber(resolve, reject) { try { setTimeout( function() { const randomInt = Date.now(); const value = randomInt % 10; try { if(value >= THRESHOLD_A) { throw new Error(`Too large: ${value}`); } } catch(msg) { reject(`Error in callback ${msg}`); } resolve(value); return; }, 500); // To experiment with error at set-up, uncomment the following 'throw'. // throw new Error("Bad setup"); } catch(err) { reject(`Error during setup: ${err}`); } return; } function determineParity(value) { const isOdd = value % 2 ? true : false ; const parityInfo = { theNumber: value, isOdd: isOdd }; return parityInfo; } function troubleWithGetNumber(reason) { console.error(`Trouble getting number: ${reason}`); throw -999; // must "throw" something, to maintain error state down the chain } function promiseGetWord(parityInfo) { // The "tetheredGetWord()" function gets "parityInfo" as closure variable. var tetheredGetWord = function(resolve,reject) { const theNumber = parityInfo.theNumber; const threshold_B = THRESHOLD_A - 1; if(theNumber >= threshold_B) { reject(`Still too large: ${theNumber}`); } else { parityInfo.wordEvenOdd = parityInfo.isOdd ? 'odd' : 'even'; resolve(parityInfo); } return; } return new Promise(tetheredGetWord); } (new Promise(tetheredGetNumber)) .then(determineParity,troubleWithGetNumber) .then(promiseGetWord) .then((info) => { console.log("Got: ",info.theNumber," , ", info.wordEvenOdd); return info; }) .catch((reason) => { if(reason === -999) { console.error("Had previously handled error"); } else { console.error(`Trouble with promiseGetWord(): ${reason}`); } }) .finally((info) => console.log("All done"));
Advanced Example
<button id="btn">Make a promise!</button> <div id="log"></div>
This small example shows the mechanism of a Promise
. The testPromise()
method is called each time the <button>
is clicked. It creates a promise that will be fulfilled, using window.setTimeout()
, to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise()
constructor is used to create the promise.
The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then()
. A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.
"use strict"; var promiseCount = 0; function testPromise() { let thisPromiseCount = ++promiseCount; let log = document.getElementById('log'); // begin log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Started (Sync code started)'); // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) let p1 = new Promise((resolve, reject) => { // The executor function is called with the ability to resolve or reject the promise log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise started (Async code started)'); // This is only an example to create asynchronism window.setTimeout(function() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); }); // We define what to do when the promise is resolved with the then() call, // and what to do when the promise is rejected with the catch() call p1.then(function(val) { // Log the fulfillment value log.insertAdjacentHTML('beforeend', val + ') Promise fulfilled (Async code terminated)'); }).catch((reason) => { // Log the rejection reason console.log(`Handle rejected promise (${reason}) here.`); }); // end log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise made (Sync code terminated)'); }
if ("Promise" in window) { let btn = document.getElementById("btn"); btn.addEventListener("click",testPromise); } else { log = document.getElementById('log'); log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; }
This example is started by clicking the button. (You need a browser that supports Promise
. )
By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.
Loading an image with XHR
Another simple example using Promise
and XMLHttpRequest
to load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Promise' in that specification. |
Browser compatibility
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Promise | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
Promise() constructor | Chrome Full support 32 | Edge Full support 12 | Firefox
Full support
29
| IE No support No | Opera Full support 19 | Safari
Full support
8
| WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android
Full support
29
| Opera Android Full support 19 | Safari iOS
Full support
8
| Samsung Internet Android Full support 2.0 | nodejs
Full support
0.12
|
all() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
allSettled() | Chrome Full support 76 | Edge Full support 79 | Firefox Full support 71 | IE No support No | Opera Full support 63 | Safari Full support 13 | WebView Android Full support 76 | Chrome Android Full support 76 | Firefox Android No support No | Opera Android Full support 54 | Safari iOS Full support 13 | Samsung Internet Android No support No | nodejs Full support 12.9.0 |
any | Chrome Full support 85 | Edge No support No | Firefox Full support 79 | IE No support No | Opera No support No | Safari Full support 14 | WebView Android Full support 85 | Chrome Android Full support 85 | Firefox Android No support No | Opera Android No support No | Safari iOS Full support 14 | Samsung Internet Android No support No | nodejs No support No |
catch() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
finally() | Chrome Full support 63 | Edge Full support 18 | Firefox Full support 58 | IE No support No | Opera Full support 50 | Safari Full support 11.1 | WebView Android Full support 63 | Chrome Android Full support 63 | Firefox Android Full support 58 | Opera Android Full support 46 | Safari iOS Full support 11.3 | Samsung Internet Android Full support 8.0 | nodejs Full support 10.0.0 |
race() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
reject() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
resolve() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
then() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- See implementation notes.
See also
- Using promises
- Promises/A+ specification
- Venkatraman.R - JS Promise (Part 1, Basics)
- Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)
- Venkatraman.R - Tools for Promises Unit Testing
- Jake Archibald: JavaScript Promises: There and Back Again
- Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript
- Matt Greer: JavaScript Promises ... In Wicked Detail
- Forbes Lindesay: promisejs.org
- Speed-polyfill to polyfill both promise availability and promise performance.
- Promise polyfill
- Udacity: JavaScript Promises