Promise.resolveLoading saved progress…

Promise.resolve

Implement your own version of Promise.resolve — the static method that wraps a value in a fulfilled promise. The surprising parts are the two short-circuits the spec mandates: if the input is already a promise, you return that exact same promise (identity, not a wrapper); if the input is a thenable — any object with a then method — you produce a new promise that adopts whatever the thenable eventually settles to.

Signature

// Returns a Promise that's either:
//   1. The same Promise instance, if `value` already is one.
//   2. A new Promise that adopts `value` if it's a thenable.
//   3. A new Promise fulfilled with `value` otherwise.
function promiseResolve<T>(value: T | Promise<T> | Thenable<T>): Promise<T>;

Examples

// Plain values become a fulfilled promise.
promiseResolve(42).then(console.log);          // logs 42
promiseResolve('hi').then(console.log);        // logs "hi"
promiseResolve({ a: 1 }).then(console.log);    // logs { a: 1 }

// Pass an existing promise — get the SAME reference back.
const p = Promise.resolve(1);
promiseResolve(p) === p;                       // true

// A thenable's then() is invoked; its resolve callback feeds the new promise.
const thenable = { then(resolve) { resolve(99); } };
promiseResolve(thenable).then(console.log);    // logs 99
// Thenables that resolve to another thenable chain through.
const inner = { then(resolve) { resolve('done'); } };
const outer = { then(resolve) { resolve(inner); } };
promiseResolve(outer).then(console.log);       // logs "done"

// A thenable whose then() throws — the returned promise rejects.
const bad = { then() { throw new Error('boom'); } };
promiseResolve(bad).catch(e => console.log(e.message)); // logs "boom"

Notes

  • Identity for promises. If value is already a Promise, return that exact instance — promiseResolve(p) === p must hold. Do not wrap it.
  • Thenable adoption. If value is an object/function with a callable .then, call value.then(resolve, reject) and let it drive a fresh promise. The thenable can resolve to anything — including another thenable, which must also be adopted, recursively.
  • One-shot settlement. The native resolve/reject callbacks you pass to a thenable's then are latched: only the first call counts. Subsequent calls (in either direction) are silently ignored.
  • Synchronous errors in then. If calling value.then(...) throws, the returned promise rejects with that error — but only if resolve/reject hasn't already been called first.
  • Always asynchronous. Even promiseResolve(42) resolves on a microtask, not synchronously. Code immediately after the call runs before the .then callback.
  • Use the native Promise constructor. You are wrapping the platform — new Promise((resolve, reject) => ...) is allowed (and expected). You are not writing a Promises/A+ implementation from scratch.
Loading editor…