Normalize mixed inputs
An API accepts either synchronous values or promises and should expose one consistent promise-based result.
JavaScript · Function
Promise.resolve(value) converts a value, promise, or thenable into a Promise. It reuses eligible existing promises, assimilates thenables, and fulfills with ordinary values.
Promise.resolve(value) produces a promise associated with value. Existing native Promise instances may be returned unchanged; thenables are assimilated by calling then, while ordinary values become fulfillment values, and nested promise-like layers are flattened.
Promise.resolve(value)| Name | Type | Description |
|---|---|---|
value | any | The value to resolve; it may be an ordinary value, a Promise, or a thenable. |
A Promise resolved with the supplied value, or the supplied promise when it can be reused. The resulting promise may be fulfilled, rejected, or pending while following another promise-like object.
const thenable = {
then(resolve) {
resolve(42);
},
};
const promise = Promise.resolve(thenable);
promise.then(console.log); // 42A thenable is assimilated, so the returned promise adopts the value supplied to its then method.
An API accepts either synchronous values or promises and should expose one consistent promise-based result.
Code interoperates with a promise-like object supplied by another library or implementation.
A function needs to return an immediately fulfilled promise without manually invoking the Promise constructor.
Promise-like results may be nested through multiple asynchronous layers and need one consumable promise.
It converts a value into a promise. A native promise can be returned directly, a thenable is assimilated by invoking its then method, and an ordinary value produces a fulfilled promise.
Follow-up: What happens with nested promise-like values? Their layers are flattened, so the resulting promise follows the eventual non-thenable outcome.
The argument is the value to resolve and may be an ordinary value, a Promise, or a thenable. The method returns a Promise resolved with that argument or the passed promise when identity-preserving conditions apply.
Follow-up: Can a resolved promise be rejected? Yes: resolution may make it follow a rejected promise or thenable, so resolved and fulfilled are different concepts.
A thenable is an object with a then method. Promise.resolve calls that method with resolving callbacks, allowing the returned promise to adopt the thenable's eventual state.
Follow-up: Why assimilate thenables? It lets native promises interoperate with promise-like objects from other implementations or libraries.
PromisePromise.reject()Promise.all()Promise.allSettled()Promise.prototype.then()Promise.prototype.catch()