Promise.resolve()

Baseline Widely available

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

Promise.resolve() 静态方法将 "resolves" 的一个给定值传给了 Promise。如果该值是一个承诺,则返回该承诺;如果值为 thenablePromise.resolve() 将调用 then() 方法并准备两个回调;否则返回的承诺将用该值来履行。

¥The Promise.resolve() static method "resolves" a given value to a Promise. If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

该函数将类似 Promise 的对象的嵌套层(例如,满足某个 Promise 的 Promise)扁平化为单个层 - 一个满足不可 thenable 值的 Promise。

¥This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value.

Try it

语法

¥Syntax

js
Promise.resolve(value)

参数

¥Parameters

value

由该 Promise 解决的争论。也可以是 Promise 或 thenable 来解析。

返回值

¥Return value

使用给定值或作为值传递的 Promise(如果该值是 Promise 对象)解析的 Promise。已解决的承诺可以处于任何状态 - 已履行、已拒绝或待定。例如,解决一个被拒绝的 Promise 仍然会导致被拒绝的 Promise。

¥A Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise.

描述

¥Description

Promise.resolve() 解决了一个承诺,这与履行或拒绝承诺不同。有关术语的定义,请参阅 承诺说明。简而言之,Promise.resolve() 返回一个 Promise,其最终状态取决于另一个 Promise、thenable 对象或其他值。

¥Promise.resolve() resolves a promise, which is not the same as fulfilling or rejecting the promise. See Promise description for definitions of the terminology. In brief, Promise.resolve() returns a promise whose eventual state depends on another promise, thenable object, or other value.

Promise.resolve() 是通用的并且支持子类化,这意味着它可以在 Promise 的子类上调用,并且结果将是子类类型的承诺。为此,子类的构造函数必须实现与 Promise() 构造函数相同的签名 - 接受可以使用 resolvereject 回调作为参数进行调用的单个 executor 函数。

¥Promise.resolve() is generic and supports subclassing, which means it can be called on subclasses of Promise, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the Promise() constructor — accepting a single executor function that can be called with the resolve and reject callbacks as parameters.

Promise.resolve() 特殊情况原生 Promise 实例。如果 value 属于 Promise 或子类,并且属于 value.constructor === Promise,则 value 直接由 Promise.resolve() 返回,而不创建新的 Promise 实例。否则,Promise.resolve() 本质上是 new Promise((resolve) => resolve(value)) 的简写。

¥Promise.resolve() special-cases native Promise instances. If value belongs to Promise or a subclass, and value.constructor === Promise, then value is directly returned by Promise.resolve(), without creating a new Promise instance. Otherwise, Promise.resolve() is essentially a shorthand for new Promise((resolve) => resolve(value)).

大部分解析逻辑实际上是由 Promise() 构造函数传递的 resolve 函数 实现的。总之:

¥The bulk of the resolving logic is actually implemented by the resolve function passed by the Promise() constructor. In summary:

  • 如果传递了非 thenable 值,则返回的 Promise 已用该值实现。
  • 如果传递了 thenable,则返回的 Promise 将通过调用 then 方法并传递一对解析函数作为参数来采用该 thenable 的状态。(但是因为原生 Promise 直接传递 Promise.resolve() 而不创建封装器,所以不会在原生 Promise 上调用 then 方法。)如果 resolve 函数接收到另一个 thenable 对象,它将再次被解析,因此 Promise 的最终实现值将永远不会是 thenable。

示例

¥Examples

使用静态 Promise.resolve 方法

¥Using the static Promise.resolve method

js
Promise.resolve("Success").then(
  (value) => {
    console.log(value); // "Success"
  },
  (reason) => {
    // not called
  },
);

解析数组

¥Resolving an array

js
const p = Promise.resolve([1, 2, 3]);
p.then((v) => {
  console.log(v[0]); // 1
});

解决另一个 Promise

¥Resolving another Promise

Promise.resolve() 重用现有的 Promise 实例。如果它正在解析原生 Promise,它将返回相同的 Promise 实例,而不创建封装器。

¥Promise.resolve() reuses existing Promise instances. If it's resolving a native promise, it returns the same promise instance without creating a wrapper.

js
const original = Promise.resolve(33);
const cast = Promise.resolve(original);
cast.then((value) => {
  console.log(`value: ${value}`);
});
console.log(`original === cast ? ${original === cast}`);

// Logs, in order:
// original === cast ? true
// value: 33

日志顺序颠倒是由于 then 处理程序是异步调用的。有关详细信息,请参阅 then() 参考。

¥The inverted order of the logs is due to the fact that the then handlers are called asynchronously. See the then() reference for more information.

解决 thenables 并抛出错误

¥Resolving thenables and throwing Errors

js
// Resolving a thenable object
const p1 = Promise.resolve({
  then(onFulfill, onReject) {
    onFulfill("fulfilled!");
  },
});
console.log(p1 instanceof Promise); // true, object casted to a Promise

p1.then(
  (v) => {
    console.log(v); // "fulfilled!"
  },
  (e) => {
    // not called
  },
);

// Thenable throws
// Promise rejects
const p2 = Promise.resolve({
  then() {
    throw new TypeError("Throwing");
  },
});
p2.then(
  (v) => {
    // not called
  },
  (e) => {
    console.error(e); // TypeError: Throwing
  },
);

// Thenable throws after callback
// Promise resolves
const p3 = Promise.resolve({
  then(onFulfilled) {
    onFulfilled("Resolving");
    throw new TypeError("Throwing");
  },
});
p3.then(
  (v) => {
    console.log(v); // "Resolving"
  },
  (e) => {
    // not called
  },
);

嵌套的 thenables 将是单个 Promise 的 "深深地压扁"。

¥Nested thenables will be "deeply flattened" to a single promise.

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

Promise.resolve(thenable).then((v) => {
  console.log(v); // 42
});

警告:不要在解析为自身的 thenable 上调用 Promise.resolve()。这会导致无限递归,因为它试图扁平化无限嵌套的承诺。

¥Warning: Do not call Promise.resolve() on a thenable that resolves to itself. That leads to infinite recursion, because it attempts to flatten an infinitely-nested promise.

js
const thenable = {
  then(onFulfilled, onRejected) {
    onFulfilled(thenable);
  },
};

Promise.resolve(thenable); // Will lead to infinite recursion.

在非 Promise 构造函数上调用 resolve()

¥Calling resolve() on a non-Promise constructor

Promise.resolve() 是通用方法。可以在任何实现与 Promise() 构造函数相同签名的构造函数上调用它。例如,我们可以在将 console.log 作为 resolve 传递的构造函数上调用它:

¥Promise.resolve() is a generic method. It can be called on any constructor that implements the same signature as the Promise() constructor. For example, we can call it on a constructor that passes it console.log as resolve:

js
class NotPromise {
  constructor(executor) {
    // The "resolve" and "reject" functions behave nothing like the
    // native promise's, but Promise.resolve() calls them in the same way.
    executor(
      (value) => console.log("Resolved", value),
      (reason) => console.log("Rejected", reason),
    );
  }
}

Promise.resolve.call(NotPromise, "foo"); // Logs "Resolved foo"

展平嵌套 thenable 的能力是由 Promise() 构造函数的 resolve 函数实现的,因此,如果你在另一个构造函数上调用它,则嵌套 thenable 可能不会展平,具体取决于该构造函数如何实现其 resolve 函数。

¥The ability to flatten nested thenables is implemented by the resolve function of the Promise() constructor, so if you call it on another constructor, nested thenables may not be flattened, depending on how that constructor implements its resolve function.

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

Promise.resolve.call(NotPromise, thenable); // Logs "Resolved { then: [Function: then] }"

规范

Specification
ECMAScript Language Specification
# sec-promise.resolve

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also