Reading a file or fetching data takes time, but JavaScript does not need to block its single thread while it waits. A promise is an object representing the eventual outcome of an operation. Unlike a callback supplied at the start of an operation, the promise can be passed around so other code can attach handlers later. section 3.1 section 8.1
A one-second timer
const timer = new Promise((resolve) => { setTimeout(resolve, 1_000); }); timer.then(() => console.log("One second has elapsed")); The executor passed to new Promise runs immediately. The timer calls resolve later; only then does the attached handler handle the result. More than one handler can be attached to the same promise. section 8.1 section 8.1.1
The rules behind that small example:
- A promise starts pending and can become fulfilled with a value or rejected with a reason. Once settled, its state and value cannot change. Calling reject or throwing in the executor rejects it; resolving with a thenable instead makes its outcome follow that thenable. section 8.1.1
- then(onFulfilled, onRejected) attaches handlers and returns a new promise. A handler’s returned value or promise determines the new outcome; a thrown error rejects it. Chain then calls for successive operations, use catch for errors along the chain, and finally for work after either outcome. section 8.1.2
- Promise.all combines operations when every result is needed and rejects if any fails. Promise.allSettled waits for every outcome; Promise.any takes the first fulfillment; Promise.race takes the first settlement. section 8.1.3
For a sequence of promise-based operations, await can make code read more like synchronous code without blocking the thread. It also avoids some nesting, though plain promise chains remain useful. With async, a function always returns a promise. section 8.2.1 section 8.4
Listing 8.5 Using Promise.race to enforce a timeout
const fetchController = new AbortController(); #A
const fetchPromise = fetch("https://httpbin.org/delay/2", { #B
signal: fetchController.signal, #B
}).then((response) => { #B
if (!response.ok) { #B
throw new Error(`Status code ${response.status}`); #B
} #B
return response.json(); #B
});
const timeoutPromise = new Promise((_, reject) => #C
setTimeout(() => { #C
fetchController.abort(); #C
reject(new Error("Request timeout"));
}, 1_000), #C
); #C
Promise.race([fetchPromise, timeoutPromise]) #D
.then((result) => {
console.log(result);
})
.catch((reason) => {
console.error(`Request failed: ${reason}`);
});
A fetch competes with a timeout through Promise.race. The timeout also aborts the request: racing outcomes alone is not the same as stopping the other operation. section 8.1.3










