Promise

BaselineWidely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers sinceJuly 2015.

ThePromiseobject 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 readUsing promisesfirst.

Description

APromiseis 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 apromiseto supply the value at some point in the future.

APromiseis 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.

Theeventual stateof a pending promise can either befulfilledwith a value orrejectedwith a reason (error). When either of these options occur, the associated handlers queued up by a promise'sthenmethod 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.

A promise is said to besettledif it is either fulfilled or rejected, but not pending.

Flowchart showing how the Promise state transitions between pending, fulfilled, and rejected via then/catch handlers. A pending promise can become either fulfilled or rejected. If fulfilled, the "on fulfillment" handler, or first parameter of the then() method, is executed and carries out further asynchronous actions. If rejected, the error handler, either passed as the second parameter of the then() method or as the sole parameter of the catch() method, gets executed.

You will also hear the termresolvedused with promises — this means that the promise is settled or "locked-in" to match the eventual state of another promise, and further resolving or rejecting it has no effect. TheStates and fatesdocument from the original Promise proposal contains more details about promise terminology. Colloquially, "resolved" promises are often equivalent to "fulfilled" promises, but as illustrated in "States and fates", resolved promises can be pending or rejected as well. For example:

js
newPromise((resolveOuter)=>{
resolveOuter(
newPromise((resolveInner)=>{
setTimeout(resolveInner,1000);
}),
);
});

This promise is alreadyresolvedat the time when it's created (because theresolveOuteris called synchronously), but it is resolved with another promise, and therefore won't befulfilleduntil 1 second later, when the inner promise fulfills. In practice, the "resolution" is often done behind the scenes and not observable, and only its fulfillment or rejection are.

Note: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 using a function with no arguments e.g.f = () => expressionto create the lazily-evaluated expression, andf()to evaluate the expression immediately.

Promiseitself has no first-class protocol for cancellation, but you may be able to directly cancel the underlying asynchronous operation, typically usingAbortController.

Chained Promises

The promise methodsthen(),catch(),andfinally()are used to associate further action with a promise that becomes settled. Thethen()method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Thecatch()andfinally()methods callthen()internally and make error handling less verbose. For example, acatch()is really just athen()without passing the fulfillment handler. As these methods return promises, they can be chained. For example:

js
constmyPromise=newPromise((resolve,reject)=>{
setTimeout(()=>{
resolve("foo");
},300);
});

myPromise
.then(handleFulfilledA,handleRejectedA)
.then(handleFulfilledB,handleRejectedB)
.then(handleFulfilledC,handleRejectedC);

We will use the following terminology:initial promiseis the promise on whichthenis called;new promiseis the promise returned bythen.The two callbacks passed tothenare calledfulfillment handlerandrejection handler,respectively.

The settled state of the initial promise determines which handler to execute.

  • If the initial promise is fulfilled, the fulfillment handler is called with the fulfillment value.
  • If the initial promise is rejected, the rejection handler is called with the rejection reason.

The completion of the handler function determines the settled state of the new promise.

  • If the handler function returns athenablevalue, the new promise settles in the same state as the returned promise.
  • If the handler function returns a non-thenable value, the new promise is fulfilled with the returned value.
  • If the handler function throws an error, the new promise is rejected with the thrown error.
  • If the initial promise has no corresponding handler attached, the new promise will settle to the same state as the initial promise — that is, without a rejection handler, a rejected promise stays rejected with the same reason.

For example, in the code above, ifmyPromiserejects,handleRejectedAwill be called, and ifhandleRejectedAcompletes normally (without throwing or returning a rejected promise), the promise returned by the firstthenwill be fulfilled instead of staying rejected. Therefore, if an error must be handled immediately, but we want to maintain the error state down the chain, we must throw an error of some type in the rejection handler. On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until the finalcatch()handler.

js
myPromise
.then(handleFulfilledA)
.then(handleFulfilledB)
.then(handleFulfilledC)
.catch(handleRejectedAny);

Usingarrow functionsfor the callback functions, implementation of the promise chain might look something like this:

js
myPromise
.then((value)=>`${value}and bar`)
.then((value)=>`${value}and bar again`)
.then((value)=>`${value}and again`)
.then((value)=>`${value}and again`)
.then((value)=>{
console.log(value);
})
.catch((err)=>{
console.error(err);
});

Note:For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence.

JavaScript maintains ajob queue.Each time, JavaScript picks a job from the queue and executes it to completion. The jobs are defined by the executor of thePromise()constructor, the handlers passed tothen,or any platform API that returns a promise. The promises in a chain represent the dependency relationship between these jobs. When a promise settles, the respective handlers associated with it are added to the back of the job queue.

A promise can participate in more than one chain. For the following code, the fulfillment ofpromiseAwill cause bothhandleFulfilled1andhandleFulfilled2to be added to the job queue. BecausehandleFulfilled1is registered first, it will be invoked first.

js
constpromiseA=newPromise(myExecutorFunc);
constpromiseB=promiseA.then(handleFulfilled1,handleRejected1);
constpromiseC=promiseA.then(handleFulfilled2,handleRejected2);

An action can be assigned to an already settled promise. In this case, the action is added immediately to the back of the job queue and will be performed when all existing jobs are completed. Therefore, an action for an already "settled" promise will occur only after the current synchronous code completes and at least one loop-tick has passed. This guarantees that promise actions are asynchronous.

js
constpromiseA=newPromise((resolve,reject)=>{
resolve(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

Thenables

The JavaScript ecosystem had made multiple Promise implementations long before it became part of the language. Despite being represented differently internally, at the minimum, all Promise-like objects implement theThenableinterface. A thenable implements the.then()method, which is called with two callbacks: one for when the promise is fulfilled, one for when it's rejected. Promises are thenables as well.

To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example,Promise.resolvewill not only resolve promises, but also trace thenables.

js
constaThenable={
then(onFulfilled,onRejected){
onFulfilled({
// The thenable is fulfilled with another thenable
then(onFulfilled,onRejected){
onFulfilled(42);
},
});
},
};

Promise.resolve(aThenable);// A promise fulfilled with 42

Promise concurrency

ThePromiseclass offers four static methods to facilitate async taskconcurrency:

Promise.all()

Fulfills whenallof the promises fulfill; rejects whenanyof the promises rejects.

Promise.allSettled()

Fulfills whenallpromises settle.

Promise.any()

Fulfills whenanyof the promises fulfills; rejects whenallof the promises reject.

Promise.race()

Settles whenanyof the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.

All these methods take aniterableof promises (thenables,to be exact) and return a new promise. They all support subclassing, which means they can be called on subclasses ofPromise,and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as thePromise()constructor — accepting a singleexecutorfunction that can be called with theresolveandrejectcallbacks as parameters. The subclass must also have aresolvestatic method that can be called likePromise.resolve()to resolve values to promises.

Note that JavaScript issingle-threadedby nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent.Parallel executionin JavaScript can only be achieved throughworker threads.

Constructor

Promise()

Creates a newPromiseobject. The constructor is primarily used to wrap functions that do not already support promises.

Static properties

Promise[@@species]

Returns the constructor used to construct return values from promise methods.

Static methods

Promise.all()

Takes an iterable of promises as input and returns a singlePromise.This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises reject, with this first rejection reason.

Promise.allSettled()

Takes an iterable of promises as input and returns a singlePromise.This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Promise.any()

Takes an iterable of promises as input and returns a singlePromise.This returned promise fulfills when any of the input's promises fulfill, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with anAggregateErrorcontaining an array of rejection reasons.

Promise.race()

Takes an iterable of promises as input and returns a singlePromise.This returned promise settles with the eventual state of the first promise that settles.

Promise.reject()

Returns a newPromiseobject that is rejected with the given reason.

Promise.resolve()

Returns aPromiseobject that is resolved with the given value. If the value is a thenable (i.e. has athenmethod), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

Promise.withResolvers()

Returns an object containing a newPromiseobject and two functions to resolve or reject it, corresponding to the two parameters passed to the executor of thePromise()constructor.

Instance properties

These properties are defined onPromise.prototypeand shared by allPromiseinstances.

Promise.prototype.constructor

The constructor function that created the instance object. ForPromiseinstances, the initial value is thePromiseconstructor.

Promise.prototype[@@toStringTag]

The initial value of the@@toStringTagproperty is the string"Promise".This property is used inObject.prototype.toString().

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.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.

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 handleronFulfilledoronRejectedis not a function).

Examples

Basic Example

js
constmyFirstPromise=newPromise((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 HTML API.
setTimeout(()=>{
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-writtennew 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 functiontetheredGetNumber()shows that a promise generator will utilizereject()while setting up an asynchronous call, or within the call-back, or both. The functionpromiseGetWord()illustrates how an API function might generate and return a promise in a self-contained manner.

Note that the functiontroubleWithGetNumber()ends with athrow.That is forced because a promise chain goes through all the.then()promises, even after an error, and without thethrow,the error would seem "fixed". This is a hassle, and for this reason, it is common to omitonRejectedthroughout the chain of.then()promises, and just have a singleonRejectedin the finalcatch().

This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change thethresholdvalues.

js
// To experiment with error handling, "threshold" values cause errors randomly
constTHRESHOLD_A=8;// can use zero 0 to guarantee error

functiontetheredGetNumber(resolve,reject){
setTimeout(()=>{
constrandomInt=Date.now();
constvalue=randomInt%10;
if(value<THRESHOLD_A){
resolve(value);
}else{
reject(`Too large:${value}`);
}
},500);
}

functiondetermineParity(value){
constisOdd=value%2===1;
return{value,isOdd};
}

functiontroubleWithGetNumber(reason){
consterr=newError("Trouble getting number",{cause:reason});
console.error(err);
throwerr;
}

functionpromiseGetWord(parityInfo){
returnnewPromise((resolve,reject)=>{
const{value,isOdd}=parityInfo;
if(value>=THRESHOLD_A-1){
reject(`Still too large:${value}`);
}else{
parityInfo.wordEvenOdd=isOdd?"odd":"even";
resolve(parityInfo);
}
});
}

newPromise(tetheredGetNumber)
.then(determineParity,troubleWithGetNumber)
.then(promiseGetWord)
.then((info)=>{
console.log(`Got:${info.value},${info.wordEvenOdd}`);
returninfo;
})
.catch((reason)=>{
if(reason.cause){
console.error("Had previously handled error");
}else{
console.error(`Trouble with promiseGetWord():${reason}`);
}
})
.finally((info)=>console.log("All done"));

Advanced Example

This small example shows the mechanism of aPromise.ThetestPromise()method is called each time the<button>is clicked. It creates a promise that will be fulfilled, usingsetTimeout(),to the promise count (number starting from 1) every 1-3 seconds, at random. ThePromise()constructor is used to create the promise.

The fulfillment of the promise is logged, via a fulfill callback set usingp1.then().A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the 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.

HTML

html
<buttonid="make-promise">Make a promise!</button>
<divid="log"></div>

JavaScript

js
"use strict";

letpromiseCount=0;

functiontestPromise(){
constthisPromiseCount=++promiseCount;
constlog=document.getElementById("log");
// begin
log.insertAdjacentHTML("beforeend",`${thisPromiseCount}) Started<br>`);
// We make a new promise: we promise a numeric count of this promise,
// starting from 1 (after waiting 3s)
constp1=newPromise((resolve,reject)=>{
// The executor function is called with the ability
// to resolve or reject the promise
log.insertAdjacentHTML(
"beforeend",
`${thisPromiseCount}) Promise constructor<br>`,
);
// This is only an example to create asynchronism
setTimeout(
()=>{
// 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((val)=>{
// Log the fulfillment value
log.insertAdjacentHTML("beforeend",`${val}) Promise fulfilled<br>`);
}).catch((reason)=>{
// Log the rejection reason
console.log(`Handle rejected promise (${reason}) here.`);
});
// end
log.insertAdjacentHTML("beforeend",`${thisPromiseCount}) Promise made<br>`);
}

constbtn=document.getElementById("make-promise");
btn.addEventListener("click",testPromise);

Result

Loading an image with XHR

Another simple example usingPromiseandXMLHttpRequestto load an image is available at the MDN GitHubjs-examplesrepository. You can alsosee it in action.Each step is commented on and allows you to follow the Promise and XHR architecture closely.

Incumbent settings object tracking

A settings object is anenvironmentthat provides additional information when JavaScript code is running. This includes the realm and module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one to use for a given piece of user code.

To better picture this, we can take a closer look at how the realm might be an issue. Arealmcan be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects likeArrayandError.Each settings object has its own "copy" of these and they are not shared. That can cause some unexpected behavior in relation to promises. In order to get around this, we track something called theincumbent settings object.This represents information specific to the context of the user code responsible for a certain function call.

To illustrate this a bit further we can take a look at how an<iframe>embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers:

html
<!doctypehtml><iframe></iframe>
<!-- we have a realm here -->
<script>
// we have a realm here as well
constbound=frames[0].postMessage.bind(frames[0],"some data","*");
// bound is a built-in function — there is no user
// code on the stack, so which realm do we use?
setTimeout(bound);
// this still works, because we use the youngest
// realm (the incumbent) on the stack
</script>

The same concept applies to promises. If we modify the above example a little bit, we get this:

html
<!doctypehtml><iframe></iframe>
<!-- we have a realm here -->
<script>
// we have a realm here as well
constbound=frames[0].postMessage.bind(frames[0],"some data","*");
// bound is a built in function — there is no user
// code on the stack — which realm do we use?
Promise.resolve(undefined).then(bound);
// this still works, because we use the youngest
// realm (the incumbent) on the stack
</script>

If we change this so that the<iframe>in the document is listening to post messages, we can observe the effect of the incumbent settings object:

html
<!-- y.html -->
<!doctypehtml>
<iframesrc="x.html"></iframe>
<script>
constbound=frames[0].postMessage.bind(frames[0],"some data","*");
Promise.resolve(undefined).then(bound);
</script>
html
<!-- x.html -->
<!doctypehtml>
<script>
window.addEventListener(
"message",
(event)=>{
document.querySelector("#text").textContent="hello";
// this code will only run in browsers that track the incumbent settings object
console.log(event);
},
false,
);
</script>

In the above example, the inner text of the<iframe>will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message.

Note:Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari.

Specifications

Specification
ECMAScript Language Specification
#sec-promise-objects

Browser compatibility

BCD tables only load in the browser

See also