Sub topic 4
Shortcuts: Promise.resolve and Promise.reject
This chapter assumes you know the three promise states (pending, fulfilled, rejected) and can build a promise with new Promise((resolve, reject) => ...). The examples attach handlers with .then and .catch. You only need to know that .then(fn) runs fn with the fulfillment value and .catch(fn) runs fn with the rejection reason. The next chapter covers both methods in full.
Often you already know the outcome of a promise when you create it. A value might already be in a cache, or an argument might fail validation. Writing out the full constructor for those cases is noisy. Promise.resolve and Promise.reject are static methods that create an already-decided promise in one call. They also do more than save typing, and the details matter.
The Basic Equivalence
In most cases, Promise.resolve(x) does the same thing as calling the constructor and resolving with x right away. Promise.reject(r) does the same thing as rejecting right away.
const a = Promise.resolve(42);
const b = new Promise((resolve) => resolve(42));
const c = Promise.reject(new Error('bad input'));
const d = new Promise((_, reject) => reject(new Error('bad input')));
a.then((v) => console.log('a:', v)); // a: 42
b.then((v) => console.log('b:', v)); // b: 42
c.catch((e) => console.log('c:', e.message)); // c: bad input
d.catch((e) => console.log('d:', e.message)); // d: bad inputEven though a is fulfilled the moment it is created, its handler still runs asynchronously, after the current synchronous code finishes. The promise is settled immediately. Its handlers are not called immediately. A later chapter covers the scheduling (the microtask queue), but you can rely on this rule now: a handler never runs in the same synchronous step that attaches it.
Promise.resolve Does Not Always Fulfill
The name is misleading. To resolve a promise means to fix what it will become. That target can be a plain value, or it can be another promise whose outcome gets adopted. Fulfilled is one specific final state. A resolved promise can still end up pending or rejected if it was resolved with a promise that is still pending or later rejects.
Promise.resolve(x) handles its input in three ways:
- If
xis a native promise whoseconstructorisPromise, it returnsxitself, the same object. - If
xis any other object or function with athenmethod (a thenable), it returns a new promise that adopts the thenable's outcome. - Otherwise it returns a new promise that is fulfilled with
x.
The identity rule is easy to check:
const slow = new Promise((resolve) => setTimeout(() => resolve('late'), 50));
const wrapped = Promise.resolve(slow);
console.log(wrapped === slow); // true
const failed = Promise.reject(new Error('broken'));
const stillFailed = Promise.resolve(failed);
console.log(stillFailed === failed); // true
stillFailed.catch((e) => console.log('rejected:', e.message)); // rejected: brokenPromise.resolve(failed) returns a rejected promise. Wrapping a promise in Promise.resolve never turns failure into success.
Thenables are adopted
Many libraries returned promise-like objects before native promises existed. Promise.resolve turns them into real promises:
const thenable = {
then(onFulfilled, onRejected) {
setTimeout(() => onFulfilled('from a thenable'), 10);
},
};
const p = Promise.resolve(thenable);
console.log(p === thenable); // false
console.log(p instanceof Promise); // true
p.then((v) => console.log(v)); // from a thenableThe thenable's then method is not called during Promise.resolve. It is called in a separate job afterward. That stops a badly written thenable from running code synchronously inside your call. The chapter on thenables explains adoption in more depth.
Promise.reject Never Unwraps
Promise.reject is simpler. It always creates a new rejected promise, and the argument becomes the reason unchanged. That holds even when the argument is a promise or a thenable:
const inner = Promise.resolve('ok');
const outer = Promise.reject(inner);
outer.catch((reason) => {
console.log(reason === inner); // true
console.log(reason instanceof Promise); // true
});Resolving with a promise adopts that promise. Rejecting with a promise uses the promise object itself as the reason. You will rarely want a promise as a rejection reason. If you see one, a value probably went to the wrong function.
Reject with Error objects
Any value can be a rejection reason, but you should pass an Error or one of its subclasses. An Error records a stack trace when it is created, and debugging tools, loggers and test runners expect a message and a stack.
Promise.reject('timeout').catch((r) => console.log(typeof r, r.stack)); // string undefined
Promise.reject(new Error('timeout')).catch((r) => console.log(typeof r, typeof r.stack)); // object stringWhere the Shortcuts Earn Their Place
Returning early from a promise-returning function
If a function returns a promise on its main path, it should return a promise on every path. That includes cache hits and validation failures. Callers can then use one style of handling every time.
const cache = new Map();
function getUser(id) {
if (typeof id !== 'number') {
return Promise.reject(new TypeError('id must be a number'));
}
if (cache.has(id)) {
return Promise.resolve(cache.get(id));
}
return new Promise((resolve) => {
setTimeout(() => {
const user = { id, name: `user${id}` };
cache.set(id, user);
resolve(user);
}, 50);
});
}
getUser('x').catch((err) => console.log(err.name, err.message));
// TypeError id must be a number
getUser(1).then((u) => {
console.log('first:', u.name);
console.log('before cached call');
getUser(1).then((u2) => console.log('cached:', u2.name));
console.log('after cached call');
});
// first: user1
// before cached call
// after cached call
// cached: user1Look at the output order. The cache hit returns a promise that is already fulfilled, but its handler still runs after 'after cached call'. Cached and uncached calls therefore behave the same way in time. Calling code cannot accidentally depend on the result arriving synchronously sometimes and asynchronously other times. That kind of inconsistency is a well-known source of bugs.
The validation branch uses Promise.reject and does not throw. A synchronous throw from a function that returns a promise forces callers to handle errors in two ways: try/catch around the call and .catch on the result. If they write only .catch, the thrown error escapes it.
Normalizing "maybe a promise" inputs
Some APIs accept either a value or a promise, for example a configuration option that may be computed asynchronously. Passing the input through Promise.resolve gives you one shape to work with:
function withLogging(maybePromise) {
return Promise.resolve(maybePromise).then((value) => {
console.log('got', value);
return value;
});
}
withLogging(5); // got 5
withLogging(new Promise((r) => setTimeout(() => r(6), 20))); // got 6Because of the identity rule, this costs almost nothing when the input is already a native promise.
Starting a chain and writing test stubs
Promise.resolve() with no argument gives a fulfilled promise whose value is undefined. It is a common starting point for building a chain step by step, for example in a loop that runs tasks one after another. In tests, Promise.resolve(fakeData) and Promise.reject(new Error('network down')) are quick stand-ins for network calls.
Gotchas
Detached methods lose their receiver
Both methods read this to decide which constructor to use. If you call them without Promise in front, they throw:
const values = [1, 2, 3];
try {
values.map(Promise.resolve); // `this` is undefined inside resolve
} catch (e) {
console.log(e instanceof TypeError); // true
}
const ok = values.map((v) => Promise.resolve(v)); // works
const alsoOk = values.map(Promise.resolve.bind(Promise)); // worksSubclasses and the identity check
The identity shortcut compares x.constructor with the constructor you called resolve on. A promise from a subclass therefore gets wrapped in a new promise:
class TrackedPromise extends Promise {}
const tp = TrackedPromise.resolve(1);
console.log(tp instanceof TrackedPromise); // true
console.log(Promise.resolve(tp) === tp); // false: different constructor
console.log(TrackedPromise.resolve(tp) === tp); // trueEager rejections need a handler soon
Promise.reject(...) creates a rejected promise right away. If no handler is attached before the runtime checks for unhandled rejections, Node.js (version 15 and later, by default) prints the error and exits the process. Browsers log an "Uncaught (in promise)" error. Creating a rejected promise ahead of time and adding its .catch later, for example inside a setTimeout, is enough to trigger this.
Quick Reference
| Call | Argument | Result |
|---|---|---|
| `Promise.resolve(42)` | plain value | new promise, fulfilled with 42 |
| `Promise.resolve(p)` | native `Promise` | `p` itself, in whatever state it is in |
| `Promise.resolve(thenable)` | object with `then` | new promise that adopts the thenable's outcome |
| `Promise.resolve()` | nothing | new promise, fulfilled with `undefined` |
| `Promise.reject(err)` | anything | new promise, rejected with `err` exactly as given |
| `Promise.reject(p)` | a promise | new promise, rejected with `p` as the reason (no unwrapping) |
Exercise
What does this code log, and in what order? const p = Promise.reject(new Error('x')); const q = Promise.resolve(p); console.log(q === p); q.then(() => console.log('fulfilled'), (e) => console.log('rejected', e.message)); console.log('end');
Show answer
It logs true, then end, then rejected x. Promise.resolve returns the native promise p unchanged, so q is the same rejected promise. The rejection handler runs asynchronously, after the synchronous console.log('end').
Exercise
A colleague writes function load(id) { if (!id) throw new Error('missing id'); return fetchItem(id); }, and callers use load(id).catch(handle). Why does load(undefined).catch(handle) fail to call handle, and how do you fix it without changing the callers?
Show answer
The throw happens synchronously, before any promise exists, so .catch is never reached and the error escapes to the caller as an exception. Replace the throw with return Promise.reject(new Error('missing id'));, or make load an async function so the throw becomes a rejection.
Exercise
Why does ['a', 'b'].map(Promise.reject) throw a TypeError, and what does Promise.reject(Promise.resolve(1)) reject with?
Show answer
map calls the function with this set to undefined, and Promise.reject needs this to be a constructor, so it throws a TypeError. Use (v) => Promise.reject(v) instead. Promise.reject(Promise.resolve(1)) rejects with the promise object itself and not with 1, because Promise.reject never unwraps its argument.