Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Promise() constructor

BaselineWidely available

ThePromise() constructor createsPromise objects. It is primarily used to wrap callback-based APIs that do not already support promises.

Try it

const promise1 = new Promise((resolve, reject) => {  setTimeout(() => {    resolve("foo");  }, 300);});promise1.then((value) => {  console.log(value);  // Expected output: "foo"});console.log(promise1);// Expected output: [object Promise]

Syntax

js
new Promise(executor)

Note:Promise() can only be constructed withnew. Attempting to call it withoutnew throws aTypeError.

Parameters

executor

Afunction to be executed by the constructor. It receives two functions as parameters:resolveFunc andrejectFunc. Any errors thrown in theexecutor will cause the promise to be rejected, and the return value will be neglected. The semantics ofexecutor are detailed below.

Return value

When called vianew, thePromise constructor returns a promise object. The promise object will becomeresolved when either of the functionsresolveFunc orrejectFunc are invoked. Note that if you callresolveFunc and pass another promise object as an argument, the initial promise can be said to be "resolved", but still not "settled". See thePromise description for more explanation.

Description

Traditionally (before promises), asynchronous tasks were designed as callbacks.

js
readFile("./data.txt", (error, result) => {  // This callback will be called when the task is done, with the  // final `error` or `result`. Any operation dependent on the  // result must be defined within this callback.});// Code here is immediately executed after the `readFile` request// is fired. It does not wait for the callback to be called, hence// making `readFile` "asynchronous".

To take advantage of the readability improvement and language features offered by promises, thePromise() constructor allows one to transform the callback-based API to a promise-based one.

Note:If your task is already promise-based, you likely do not need thePromise() constructor.

Theexecutor is custom code that ties an outcome in a callback to a promise. You, the programmer, write theexecutor. Its signature is expected to be:

js
function executor(resolveFunc, rejectFunc) {  // Typically, some asynchronous operation that accepts a callback,  // like the `readFile` function above}

resolveFunc andrejectFunc are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type.

js
resolveFunc(value); // call on resolvedrejectFunc(reason); // call on rejected

Thevalue parameter passed toresolveFunc can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of theresolution promise). TherejectFunc has semantics close to thethrow statement, soreason is typically anError instance. If eithervalue orreason is omitted, the promise is fulfilled/rejected withundefined.

Theexecutor's completion state has limited effect on the promise's state:

  • Theexecutor return value is ignored.return statements within theexecutor merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. Ifexecutor exits and it's impossible forresolveFunc orrejectFunc to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever.
  • If an error is thrown in theexecutor, the promise is rejected, unlessresolveFunc orrejectFunc has already been called.

Note:The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending).

Here's a summary of the typical flow:

  1. At the time when the constructor generates the newPromise object, it also generates a corresponding pair of functions forresolveFunc andrejectFunc; these are "tethered" to thePromise object.
  2. executor typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within theexecutor code, so it has access to theresolveFunc andrejectFunc.
  3. Theexecutor is called synchronously (as soon as thePromise is constructed) with theresolveFunc andrejectFunc functions as arguments.
  4. The code within theexecutor has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused byresolveFunc orrejectFunc. The side effect is that thePromise object becomes "resolved".
    • IfresolveFunc is called first, the value passed will beresolved. The promise may stay pending (in case anotherthenable is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value).
    • IfrejectFunc is called first, the promise instantly becomes rejected.
    • Once one of the resolving functions (resolveFunc orrejectFunc) is called, the promise stays resolved. Only the first call toresolveFunc orrejectFunc affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite.
    • Ifexecutor exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved).
    • Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e., settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable.
  5. Once the promise settles, it (asynchronously) invokes any further handlers associated throughthen(),catch(), orfinally(). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (seeChained Promises).

For example, the callback-basedreadFile API above can be transformed into a promise-based one.

js
const readFilePromise = (path) =>  new Promise((resolve, reject) => {    readFile(path, (error, result) => {      if (error) {        reject(error);      } else {        resolve(result);      }    });  });readFilePromise("./data.txt")  .then((result) => console.log(result))  .catch((error) => console.error("Failed to read data"));

Theresolve andreject callbacks are only available within the scope of the executor function, which means you can't access them after the promise is constructed. If you want to construct the promise before deciding how to resolve it, you can use thePromise.withResolvers() method instead, which exposes theresolve andreject functions.

The resolve function

Theresolve function has the following behaviors:

  • If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with aTypeError.
  • If it's called with a non-thenable value (a primitive, or an object whosethen property is not callable, including when the property is not present), the promise is immediately fulfilled with that value.
  • If it's called with a thenable value (including anotherPromise instance), then the thenable'sthen method is saved and called in the future (it's always called asynchronously). Thethen method will be called with two callbacks, which are two new functions with the exact same behaviors as theresolveFunc andrejectFunc passed to theexecutor function. If calling thethen method throws, then the current promise is rejected with the thrown error.

In the last case, it means code like:

js
new Promise((resolve, reject) => {  resolve(thenable);});

Is roughly equivalent to:

js
new Promise((resolve, reject) => {  try {    thenable.then(      (value) => resolve(value),      (reason) => reject(reason),    );  } catch (e) {    reject(e);  }});

Except that in theresolve(thenable) case:

  1. resolve is called synchronously, so that callingresolve orreject again has no effect, even when the handlers attached throughanotherPromise.then() are not called yet.
  2. Thethen method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed.

Becauseresolve is called again with whateverthenable.then() passes to it asvalue, the resolver function is able to flatten nested thenables, where a thenable calls itsonFulfilled handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value.

Examples

Turning a callback-based API into a promise-based one

To provide a function with promise functionality, have it return a promise by calling theresolve andreject functions at the correct times.

js
function myAsyncFunction(url) {  return new Promise((resolve, reject) => {    const xhr = new XMLHttpRequest();    xhr.open("GET", url);    xhr.onload = () => resolve(xhr.responseText);    xhr.onerror = () => reject(xhr.statusText);    xhr.send();  });}

Effect of calling resolveFunc

CallingresolveFunc causes the promise to become resolved, so that callingresolveFunc orrejectFunc again has no effect. However, the promise may be in any of the states: pending, fulfilled, or rejected.

ThispendingResolved promise is resolved the time it's created, because it has already been "locked in" to match the eventual state of the inner promise, and callingresolveOuter orrejectOuter or throwing an error later in the executor has no effect on its eventual state. However, the inner promise is still pending until 100ms later, so the outer promise is also pending:

js
const pendingResolved = new Promise((resolveOuter, rejectOuter) => {  resolveOuter(    new Promise((resolveInner) => {      setTimeout(() => {        resolveInner("inner");      }, 100);    }),  );});

ThisfulfilledResolved promise becomes fulfilled the moment it's resolved, because it's resolved with a non-thenable value. However, when it's created, it's unresolved, because neitherresolve norreject has been called yet. An unresolved promise is necessarily pending:

js
const fulfilledResolved = new Promise((resolve, reject) => {  setTimeout(() => {    resolve("outer");  }, 100);});

CallingrejectFunc obviously causes the promise to reject. However, there are also two ways to cause the promise to instantly become rejected even when theresolveFunc callback is called.

js
// 1. Resolving with the promise itselfconst rejectedResolved1 = new Promise((resolve) => {  // Note: resolve has to be called asynchronously,  // so that the rejectedResolved1 variable is initialized  setTimeout(() => resolve(rejectedResolved1)); // TypeError: Chaining cycle detected for promise #<Promise>});// 2. Resolving with an object which throws when accessing the `then` propertyconst rejectedResolved2 = new Promise((resolve) => {  resolve({    get then() {      throw new Error("Can't get then property");    },  });});

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-promise-constructor

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp