Sub topic 4
Shortcuts: Promise.resolve and Promise.reject
This chapter assumes you know the three promise states (pending, fulfilled, rejected) and how to build a promise with new Promise. You will see .then and .catch used to print results. The next chapter covers them in full.
Sometimes you need a promise that is already settled, or you need to turn a value into a promise. Writing new Promise((resolve) => resolve(x)) for this is noisy. Two static methods do the same job more clearly.
Promise.resolve: wrap a value
Promise.resolve(value) returns a promise for value. What you get back depends on what you pass in.
// A plain value: the result is a promise already fulfilled with it
Promise.resolve(42).then((v) => console.log(v)); // 42
// A native promise: the same promise object comes back, unchanged
const original = new Promise((resolve) => setTimeout(() => resolve('later'), 50));
console.log(Promise.resolve(original) === original); // true
// A rejected promise: the result is rejected too
Promise.resolve(Promise.reject(new Error('still bad')))
.catch((err) => console.log('caught:', err.message)); // caught: still badThe last case surprises many people. The name resolve does not mean "fulfill". It means "settle this promise to match whatever I was given". If you give it a rejected promise, the result is rejected.
You can also pass an object that has a then method, called a thenable. Promise.resolve adopts its outcome. A later chapter explains how that works.
Promise.reject: always rejected
Promise.reject(reason) returns a promise that is already rejected with reason. It never unwraps its argument. If you pass it a promise, that promise object becomes the rejection reason.
Promise.reject(new Error('bad input'))
.catch((err) => console.log(err.message)); // bad input
Promise.reject(Promise.resolve(1))
.catch((reason) => console.log(reason instanceof Promise)); // true| Call | Argument | Result |
|---|---|---|
| `Promise.resolve(5)` | plain value | fulfilled with 5 |
| `Promise.resolve(p)` | native promise | `p` itself |
| `Promise.resolve(rejected)` | rejected promise | rejected |
| `Promise.reject(err)` | any value | rejected with `err` |
| `Promise.reject(p)` | a promise | rejected with `p` as the reason |
Where the shortcuts help
The most common use is a function that must always return a promise, even when it can answer straight away. Callers can then treat every outcome the same way.
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)); // answer now, still as a promise
}
return new Promise((resolve) => {
setTimeout(() => {
const user = { id, name: `user${id}` };
cache.set(id, user);
resolve(user);
}, 100);
});
}
getUser(1)
.then((u) => console.log('first:', u.name)) // after ~100 ms
.then(() => getUser(1))
.then((u) => console.log('cached:', u.name)); // from the cache
getUser('x').catch((err) => console.log(err.message)); // id must be a numberIf the validation branch used throw, the error would be thrown synchronously, and a caller using only .catch would miss it. Returning Promise.reject means every failure arrives the same way.
Promise.resolve() with no argument is also a common way to start a chain, and it is handy in tests when you need a stub that returns a fulfilled promise.
Common errors
- Assuming
Promise.resolvealways fulfills. It follows promises and thenables, so the result can be rejected. - Creating a
Promise.rejectwith no handler. A rejected promise that nothing handles triggers an unhandled rejection warning, and in Node.js it ends the process by default. - Rejecting with strings.
Promise.reject('oops')works, but you lose the stack trace. Reject withErrorobjects. - Wrapping a promise again for no reason.
Promise.resolve(p)on a native promise just gives backp, so the wrapper adds nothing.
Exercise
What does this code log, and why? const p = Promise.reject(new Error('e')); const q = Promise.resolve(p); console.log(p === q); q.catch((err) => console.log(err.message));
Show answer
It logs true, then e. Promise.resolve returns a native promise unchanged, so q is the same object as p. That object is rejected, so the catch handler runs with the error whose message is "e".
Exercise
A function loadConfig(path) returns a promise, but it throws a TypeError synchronously when path is empty. Why is that a problem, and how would you fix it?
Show answer
Callers who handle errors only with .catch will not catch the synchronous throw, so it escapes as an ordinary exception. Return Promise.reject(new TypeError('path is required')) instead, so every failure arrives as a rejection.