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 with a callback. It also builds on the previous chapter: a promise starts pending and settles once, as either fulfilled with a value or rejected with a reason. Here you learn how to make that settlement happen yourself with the Promise constructor. You also learn which mistakes inside the constructor quietly break your code.
The Constructor and Its Executor
You create a promise by calling new Promise with one function, called the executor. JavaScript calls the executor immediately and passes it two functions: resolve and reject. Calling resolve(value) fulfills the promise. Calling reject(reason) rejects it.
The most common use is wrapping something 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 msdelay returns a promise right away, and that promise is pending. About 100 ms later the timer callback calls resolve('done'), and the promise becomes fulfilled. The .then handler covered in a later chapter receives the value. The executor is the only place that has access to resolve and reject (unless you pass them out on purpose), so only the code that created the promise can settle it.
The names resolve and reject are only a convention. You can name the parameters anything, and you can leave out the second one if the operation can never fail, as delay does.
The Executor Runs Synchronously
A common misconception is that the executor runs "in the background." It doesn't. It runs right away, before new Promise returns:
console.log('before');
const p = new Promise((resolve) => {
console.log('executor');
resolve('x');
});
console.log('after');
p.then((v) => console.log(v));
// Output:
// before
// executor
// after
// xThe promise is already fulfilled by the time 'after' prints. The .then callback still runs last, because promise reactions always run asynchronously. The microtask chapter explains exactly when. Two things follow from this:
- Heavy synchronous work inside an executor blocks the thread just like any other code. A promise does not move work to another thread.
- The executor is the place to start an asynchronous operation (a timer, a file read, a network request). That operation's callback settles the promise later.
First Settlement Wins
A promise settles once. After the first resolve or reject, every later call does nothing. No error is thrown, and no warning is shown:
const p = new Promise((resolve, reject) => {
resolve('first');
resolve('second'); // ignored
reject(new Error('late')); // ignored
});
p.then((v) => console.log(v)); // firstThis guarantee lets you write executors with several exit paths without tracking state yourself. For example, a timer and a success callback can race to settle the same promise, and only the first one counts. The downside is that a bug that settles twice goes unnoticed. If you expected the second call to matter, nothing will tell you it was dropped.
Calling resolve or reject does not stop the executor. Code after the call still runs:
new Promise((resolve) => {
resolve(1);
console.log('still running'); // this prints
});Write return resolve(value); when you want to leave the executor at that point. This is common inside if branches.
Throwing Inside the Executor
If the executor throws synchronously before settling, 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('rejected:', err.message)); // rejected: bad inputIf the executor has already settled the promise, a later throw is swallowed, because first settlement wins:
const q = new Promise((resolve) => {
resolve('ok');
throw new Error('never seen');
});
q.then((v) => console.log(v)); // okErrors in Async Callbacks Escape
The constructor catches only errors thrown while the executor itself is running. A callback that runs later, such as a timer or I/O callback, runs on a fresh call stack outside the constructor's protection. An error thrown there does not reject the promise. It becomes an uncaught exception, and the promise stays pending forever.
// Broken: the throw happens inside the timer callback, after the executor returned.
// In Node.js this crashes the process with "Error: lost"; the promise never settles.
new Promise((resolve) => {
setTimeout(() => {
throw new Error('lost');
}, 0);
});The fix is to catch inside the callback and route the error to reject:
function parseLater(text) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(JSON.parse(text));
} catch (err) {
reject(err);
}
}, 0);
});
}
parseLater('{"a": 1}').then((obj) => console.log(obj.a)); // 1
parseLater('not json').catch((err) => console.log(err.name)); // SyntaxErrorWhat resolve and reject Accept
| Call | Result |
|---|---|
| `resolve(42)` | Fulfilled with `42` |
| `resolve()` | Fulfilled with `undefined` |
| `resolve(otherPromise)` | Follows `otherPromise`: stays pending until it settles, then takes its outcome |
| `reject(new Error('x'))` | Rejected with the Error object |
| `reject(otherPromise)` | Rejected with the promise object itself, which is not unwrapped |
| `return 42` from the executor | Ignored; the promise is unaffected |
Three rows deserve comment.
Resolving with a promise does not fulfill with that promise. The new promise locks onto the other one and copies its result. That is why "resolve" and "fulfill" are different words. A promise that has been resolved with a pending promise is still pending, and it can end up rejected:
const inner = new Promise((_, reject) => setTimeout(() => reject(new Error('inner failed')), 50));
const outer = new Promise((resolve) => resolve(inner));
outer.catch((err) => console.log(err.message)); // inner failedThe chapter on thenables explains how this adoption works and why it also applies to any object with a then method.
Always reject with an Error. You can reject with any value, but an Error carries a stack trace and a message, and code that handles errors usually expects one. reject('timeout') makes debugging harder than reject(new Error('timeout')).
The executor's return value is ignored. If you mark the executor async, it returns a promise that the constructor throws away. Any rejection of that promise is lost, and so is any error thrown after its first await. Avoid new Promise(async (resolve, reject) => { ... }). Write a plain async function instead.
Misuse the Constructor Rejects
The constructor checks two things and throws a TypeError synchronously. That error is not turned into a rejected promise:
try {
Promise((resolve) => resolve(1)); // missing `new`
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
new Promise(); // executor is not a function
} catch (err) {
console.log(err instanceof TypeError); // true
}A Realistic Executor: Validation, Success and Failure
This simulated lookup combines everything above. It validates its input synchronously, starts a timer, and settles from the callback:
const users = { 1: 'Ada', 2: 'Linus' };
function fetchUser(id) {
return new Promise((resolve, reject) => {
if (!Number.isInteger(id)) {
// Synchronous validation; `return` stops the executor.
return reject(new TypeError(`id must be an integer, got ${id}`));
}
setTimeout(() => {
const name = users[id];
if (name === undefined) {
reject(new Error(`user ${id} not found`));
} else {
resolve({ id, name });
}
}, 30);
});
}
fetchUser(1).then((u) => console.log(u.name)); // Ada
fetchUser(9).catch((err) => console.log(err.message)); // user 9 not found
fetchUser('x').catch((err) => console.log(err.message)); // id must be an integer, got xThe function always returns a promise, even for bad input. Callers then handle every failure in one place, without having to wrap the call in a separate try/catch for synchronous errors.
Settling from Outside: Deferreds and Promise.withResolvers
Sometimes the code that settles a promise doesn't fit inside the executor, for example a request/response protocol where the reply arrives through a separate event handler. Because the executor runs synchronously, you can copy resolve and reject into outer variables:
function createDeferred() {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
const d = createDeferred();
d.promise.then((v) => console.log('got', v));
setTimeout(() => d.resolve('reply'), 20); // got replyES2024 standardized this pattern as Promise.withResolvers(). It is available in current browsers and Node.js 22+:
const { promise, resolve } = Promise.withResolvers();
promise.then((v) => console.log(v)); // ready
resolve('ready');When Not to Use new Promise
The constructor exists to wrap things that are not promises yet: timers, events and callback APIs. If you already have a promise, such as the result of fetch or of another function that returns a promise, wrapping it in new Promise adds code and makes it easy to drop errors. Return or chain the existing promise instead. The pitfalls chapter covers this anti-pattern in detail. The chapter on wrapping callback APIs shows the standard way to convert error-first callbacks.
Exercise
What does this code log, and in what order? const p = new Promise((resolve, reject) => { console.log('A'); reject(new Error('B')); resolve('C'); console.log('D'); }); p.then((v) => console.log(v), (e) => console.log(e.message)); console.log('E');
Show answer
A, D, E, B. The executor runs synchronously and logs A. reject settles the promise as rejected, resolve('C') is ignored, and D still logs because calling reject does not stop the executor. E logs next as synchronous code. The rejection handler runs asynchronously afterwards and logs B.
Exercise
A colleague writes function wait(ms) { return new Promise((resolve) => { setTimeout(() => { if (ms > 1000) throw new Error('too long'); resolve(); }, ms); }); }. Calling wait(2000).catch(console.error) never logs the error. Why, and how do you fix it?
Show answer
The throw happens inside the timer callback, after the executor has returned, so the Promise constructor cannot catch it. It becomes an uncaught exception and the promise stays pending forever. Replace the throw with return reject(new Error('too long')); and add reject as the executor's second parameter. Alternatively, check ms synchronously in the executor, before calling setTimeout.
Exercise
Given const inner = new Promise((r) => setTimeout(() => r('late'), 100)); const outer = new Promise((resolve) => resolve(inner));, what state is outer in immediately after this code runs, and with what value does it eventually settle?
Show answer
outer is still pending. Resolving with a promise makes outer follow inner instead of fulfilling with the promise object. After about 100 ms, inner fulfills with 'late' and outer fulfills with 'late' too.