Sub topic 2
Promises: Pending, Fulfilled, and Rejected
This chapter assumes you can write functions and arrow functions, pass callbacks, and run JavaScript in Node.js or a browser console. You also need to know from the previous chapter that the event loop runs callbacks later, once the current code finishes.
A Promise is an object that stands for a value that is not ready yet. An asynchronous operation, such as a timer, a file read, or a network request, hands you a Promise straight away. Later the Promise tells you whether the operation succeeded and gives you the result.
The three states
Every Promise is in exactly one of three states at any moment:
| State | Meaning | Carries |
|---|---|---|
| pending | The operation has not finished | Nothing yet |
| fulfilled | The operation succeeded | A value |
| rejected | The operation failed | A reason, usually an `Error` |
A Promise that is fulfilled or rejected is called settled. Settling happens only once. After a Promise settles, its state and value never change.
Creating a Promise
The Promise constructor takes one function, called the executor. JavaScript runs the executor immediately and passes it two functions: resolve and reject. You call one of them when the work finishes.
function delay(ms, value) {
return new Promise((resolve, reject) => {
if (ms < 0) {
reject(new Error('ms must not be negative'));
return;
}
setTimeout(() => resolve(value), ms);
});
}
const p = delay(500, 'ready');
console.log(p); // Promise { <pending> } in Node.js
p.then(value => console.log('fulfilled with', value));
delay(-1, 'never').catch(err => console.log('rejected:', err.message));The executor runs synchronously, and the then and catch callbacks run later. Here rejected: ms must not be negative prints first, and fulfilled with ready prints about half a second after that. A then callback always runs asynchronously, even when the Promise has already settled.
If the executor throws, the Promise is rejected with the thrown error. You do not need to wrap the executor body in try/catch yourself.
const broken = new Promise(() => {
throw new Error('boom');
});
broken.catch(err => console.log(err.message)); // boomShortcuts for settled Promises
When you already have the value, Promise.resolve and Promise.reject give you a Promise without writing an executor.
Promise.resolve(42).then(v => console.log(v)); // 42
Promise.reject(new Error('nope')).catch(e => console.log(e.message)); // nopeIf you pass a Promise to Promise.resolve, you get that same Promise back. Calling resolve inside an executor works the same way. Resolving with another Promise makes the outer Promise follow it, so the outer one settles however the inner one settles.
Common errors
Settling more than once
Later calls to resolve or reject are ignored without any error message, so this bug can be hard to spot.
new Promise((resolve, reject) => {
resolve('first');
resolve('second'); // ignored
reject(new Error('too late')); // ignored
}).then(v => console.log(v)); // firstAdd a return after reject so the code after it does not keep running, as delay does above.
Never settling
If no code path calls resolve or reject, the Promise stays pending forever. Its callbacks never run, and anything waiting on it hangs without an error.
Rejecting with something other than an Error
reject('failed') works, but a string has no stack trace. Reject with an Error object so that whoever handles the failure can see where it came from.
The next chapter shows how then, catch, and finally return new Promises that you can chain together.
Exercise
What does this code print, and in what order? const p = new Promise((resolve, reject) => { console.log('executor'); reject(new Error('x')); resolve('y'); }); p.then(v => console.log('value', v)).catch(e => console.log('error', e.message)); console.log('after');
Show answer
It prints "executor", then "after", then "error x". The executor runs synchronously, so "executor" comes first. The rejection settles the Promise, and the later resolve('y') is ignored. Handlers run asynchronously, so "after" prints before the catch callback. The then callback is skipped because the Promise is rejected.
Exercise
Write a function timeout(ms) that returns a Promise which rejects with an Error whose message is "timed out" after ms milliseconds.
Show answer
const timeout = ms => new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms)); Calling timeout(100).catch(e => console.log(e.message)) prints "timed out" after about 100 ms.