Sub topic 3
Creating Promises with new Promise
This chapter assumes you know JavaScript functions, closures and arrow functions, and that you have used setTimeout. It also assumes the previous chapter's model: a promise starts pending and settles once, as either fulfilled or rejected. Here you will see how to build that object yourself with the Promise constructor.
The constructor and its executor
new Promise(executor) takes one function, called the executor. JavaScript calls the executor right away and passes it two functions, usually named resolve and reject. Calling resolve(value) fulfills the promise with value. Calling reject(reason) rejects it with reason.
The usual use is to wrap an operation that finishes later, such as a timer:
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
delay(100, 'done').then((v) => console.log(v)); // logs "done" after about 100 msThe function returns the promise straight away, while it is still pending. About 100 ms later the timer fires and resolve settles the promise. The then call is covered in a later chapter. For now, read it as "run this once the promise fulfills".
The executor runs synchronously
The executor is not deferred. It runs during the new Promise(...) call itself:
console.log('before');
const p = new Promise((resolve) => {
console.log('executor runs');
resolve(42);
});
console.log('after');
// Output: before, executor runs, afterCode that only reacts to the result runs later, but any work you start inside the executor starts immediately.
Only the first settlement counts
resolve and reject are one-shot. After the first call settles the promise, later calls do nothing and raise no error:
const p = new Promise((resolve, reject) => {
resolve('first');
resolve('second');
reject(new Error('ignored'));
});
p.then((v) => console.log(v)); // firstThat is how the constructor guarantees a settled promise never changes state.
Throwing inside the executor
If the executor throws synchronously, the constructor catches the error and rejects the promise with it:
const p = new Promise(() => {
throw new Error('bad input');
});
p.catch((err) => console.log(err.message)); // bad inputCommon mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Never calling `resolve` or `reject` on some code path | Promise stays pending forever | Make sure every branch, including error branches, settles |
| Forgetting `return` before `new Promise` in a wrapper function | Caller gets `undefined` | Return the promise |
| Rejecting with a string, such as `reject('failed')` | No stack trace, and `err.message` is undefined | Reject with an `Error` object |
| Throwing in an async callback | Uncaught exception, promise stays pending | Call `reject(err)` instead |
| Wrapping something that already returns a promise | Extra code, and errors can get lost | Use the existing promise directly |
If you pass another promise to resolve, the new promise does not fulfill with that promise as its value. It follows the other promise and settles the same way. The thenables chapter explains how this works.
Exercise
What does this code log, in what order, and what is the final state of p? const p = new Promise((resolve, reject) => { console.log('A'); setTimeout(() => { reject(new Error('late')); resolve('ok'); }, 10); console.log('B'); }); console.log('C'); p.catch((e) => console.log(e.message));
Show answer
It logs A, B, C right away, because the executor runs synchronously during the constructor call. After about 10 ms it logs "late". The reject call settles p as rejected, and the resolve call after it is ignored. p stays rejected with Error('late').
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
function timeout(ms) { return new Promise((_, reject) => { setTimeout(() => reject(new Error('timed out')), ms); }); }