Sub topic 2
Promises: Pending, Fulfilled, and Rejected
A Promise is an object that stands for a value you don't have yet. Async functions and await are built on Promises. If you understand how a Promise changes state, you can predict what await will do. This chapter covers how Promises are created, the three states they can be in, and the rules that control how they move between those states.
This chapter assumes you are comfortable with JavaScript functions (including arrow functions), callbacks, basic try/catch, and running code in Node.js or a browser console. It also assumes you have read the previous chapter, which explained that slow work such as timers and network requests is handed off so the main thread can keep running.
What a Promise represents
Before Promises, asynchronous APIs took a callback. You passed in a function, and the API called it when the work finished. That works, but each API invented its own conventions for errors, and nesting callbacks becomes hard to follow.
A Promise turns the future result into a value you can store, return from a function, and pass around. The code that starts the work hands back a Promise right away. Code that needs the result attaches handlers to that Promise.
The three states
Every Promise is in exactly one of three states:
| State | Meaning | Carries |
|---|---|---|
| pending | The work has not finished yet | nothing |
| fulfilled | The work succeeded | a value |
| rejected | The work failed | a reason (usually an `Error`) |
A Promise that is either fulfilled or rejected is called settled. Settling happens once and is permanent. A fulfilled Promise never becomes rejected, and its value never changes. This guarantee is what makes Promises safe to share: every handler that ever reads a settled Promise sees the same outcome.
You cannot read a Promise's state directly in code. There is no promise.state property. The only way to get the outcome is to register handlers, which is deliberate: it forces your code to deal with the fact that the result may not exist yet.
Creating a Promise
You build a Promise with the Promise constructor. You pass it a function called the executor, and the constructor calls it with two functions, resolve and reject:
const coinFlip = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) {
resolve('heads');
} else {
reject(new Error('tails'));
}
}, 500);
});
coinFlip.then(
value => console.log('Fulfilled with', value),
reason => console.log('Rejected with', reason.message)
);For about 500 ms, coinFlip is pending. Then the timer fires, and the code calls either resolve or reject, which settles the Promise. The .then method takes two optional handlers. The first runs on fulfillment and the second runs on rejection. The next chapter covers .then, .catch, and .finally in detail, so this chapter uses only the basic form.
The executor runs synchronously
A common wrong assumption is that the executor runs later. It doesn't. The constructor calls the executor immediately, before new Promise(...) returns. What runs later is the handlers.
console.log('1');
const p = new Promise(resolve => {
console.log('2');
resolve('4');
});
p.then(value => console.log(value));
console.log('3');
// Output: 1, 2, 3, 4The Promise is already fulfilled when .then is called, but the handler still doesn't run until the current synchronous code finishes. Handlers are always called asynchronously, even for a Promise that has already settled. Because of this rule, your code behaves the same way whether the result arrives in 0 ms or 5 seconds. The chapter on microtasks explains exactly when these handlers run.
The settlement rules
The executor's resolve and reject functions follow a few rules that often surprise people.
Only the first call counts
Once a Promise has settled, any later call to resolve or reject is silently ignored. No error is thrown.
const p = new Promise((resolve, reject) => {
resolve('first');
resolve('second'); // ignored
reject(new Error('oops')); // ignored
});
p.then(value => console.log(value)); // firstThe silence is a trade-off. It protects the guarantee that a Promise settles only once, but it can also hide bugs where two code paths both think they finished the work.
A throw inside the executor becomes a rejection
If the executor throws before it settles the Promise, the Promise is rejected with the thrown value:
const p = new Promise(() => {
JSON.parse('{ not valid json');
});
p.then(
() => console.log('never runs'),
err => console.log('Rejected:', err.name) // Rejected: SyntaxError
);This only covers code that runs synchronously inside the executor. A throw inside a setTimeout callback within the executor happens later, on a separate call stack. The Promise doesn't catch it, so it becomes an uncaught exception and the Promise stays pending forever:
const stuck = new Promise(() => {
setTimeout(() => {
throw new Error('not caught by the Promise');
}, 100);
});Inside asynchronous callbacks, catch the error yourself and call reject with it.
Resolving is not always fulfilling
Calling resolve with an ordinary value fulfills the Promise. If you pass resolve another Promise (or any thenable, meaning an object with a then method), the outer Promise instead adopts that Promise's eventual outcome. The outer Promise stays pending until the inner one settles, then copies its result.
const inner = new Promise((_, reject) =>
setTimeout(() => reject(new Error('inner failed')), 200)
);
const outer = new Promise(resolve => {
resolve(inner); // outer now follows inner
});
outer.then(
value => console.log('fulfilled', value),
err => console.log('rejected:', err.message) // rejected: inner failed
);This is why the specification uses two different words. "Resolved" means the Promise's fate is locked in, either to a value or to another Promise. "Fulfilled" means it actually has a value. A resolved Promise can still end up rejected. reject does not adopt anything: reject(somePromise) rejects with the Promise object itself as the reason.
Shortcuts: Promise.resolve and Promise.reject
Writing a full constructor just to produce an already-settled Promise is wordy, so two static helpers exist:
const ready = Promise.resolve(42);
const failed = Promise.reject(new Error('no access'));
ready.then(v => console.log('value', v)); // value 42
failed.then(null, e => console.log('error', e.message)); // error no accessPromise.resolve(x) follows the same adoption rule as resolve. If x is already a native Promise, Promise.resolve(x) returns that same object. It is useful when a function might return either a plain value or a Promise and you want to handle both the same way.
Wrapping a callback API
The main practical reason to write new Promise yourself is to wrap an older callback-based API. Node's fs.readFile uses the error-first callback convention, (err, data):
const fs = require('fs');
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
readFileAsync(__filename).then(
text => console.log('Read', text.length, 'characters'),
err => console.log('Failed:', err.code)
);The return after reject doesn't change the Promise, because a second settlement would be ignored anyway. It keeps the function from running success-path code after a failure. In practice, Node ships util.promisify and the fs/promises module for this. You still need the manual pattern for libraries that don't provide Promise versions.
Unhandled rejections
A rejected Promise that never gets a rejection handler is an unhandled rejection. Browsers log it to the console. Since Node.js 15, an unhandled rejection crashes the process by default.
Promise.reject(new Error('nobody is listening'));
// Node.js: the process exits with this errorThe runtime decides whether a rejection was handled shortly after it happens, not at the moment of rejection. You can create a rejected Promise and attach a handler in the same synchronous block without triggering the warning. If you attach the handler much later, for example inside a setTimeout, the runtime may already have reported it.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Never calling `resolve` or `reject` on some code path | The Promise stays pending forever, and handlers never run | Make sure every branch, including error branches, settles the Promise |
| Throwing inside an async callback in the executor | Uncaught exception, and the Promise stays pending | Use `try/catch` in the callback and call `reject(err)` |
| Expecting the executor to run later | Side effects happen earlier than expected | Remember the executor runs immediately during construction |
| Expecting a handler to run immediately on a settled Promise | Logs appear out of order | Handlers always run after the current synchronous code |
| Rejecting with a string | No stack trace | Reject with `new Error(...)` |
| Ignoring a rejected Promise | Console warning, or a Node.js crash | Attach a rejection handler |
Exercise
What does this code print, and in what order? const p = new Promise((resolve, reject) => { console.log('A'); reject(new Error('X')); resolve('Y'); console.log('B'); }); p.then(v => console.log('ok', v), e => console.log('err', e.message)); console.log('C');
Show answer
It prints A, B, C, then "err X". The executor runs synchronously, so A and B print during construction. The return keyword is not involved, so the code after reject still runs. The later resolve('Y') is ignored because the Promise has already been rejected. C prints next because handlers wait until the synchronous code finishes, and then the rejection handler prints "err X".
Exercise
A coworker writes function wait(ms) { return new Promise(resolve => { setTimeout(resolve(ms), ms); }); } and reports that wait(2000).then(...) fires immediately. Why, and how do you fix it?
Show answer
resolve(ms) is called right away, while the arguments to setTimeout are being evaluated. The Promise fulfills immediately, and setTimeout receives undefined as its callback. Pass a function instead: setTimeout(() => resolve(ms), ms).
Exercise
What state does outer end up in, and why? const outer = Promise.resolve(Promise.reject(new Error('bad')));
Show answer
Rejected, with the reason Error('bad'). Promise.resolve given a native Promise returns that same Promise, so outer is the rejected Promise itself. Resolving never forces fulfillment. It adopts the outcome of the Promise it is given.