Asynchronous JavaScript
Node.js Promises
A promise represents a value that is not available yet. It is pending, then either fulfilled with a value or rejected with an error, and .then/.catch/.finally attach handlers to those outcomes.
What is Promises in Node.js?
A promise represents a value that is not available yet. It is pending, then either fulfilled with a value or rejected with an error, and .then/.catch/.finally attach handlers to those outcomes.
Promises example
JavaScript
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
fetchJob(id)
.then(job => enrich(job)) // return a promise to chain
.then(job => save(job))
.catch(err => console.error(err))
.finally(() => console.log('finished'));Key points to remember
- Returning a promise inside .then chains it; forgetting to return breaks the chain.
- A rejection with no .catch becomes an unhandled rejection and terminates the process.
- Promise.allSettled is right when partial failure is acceptable.
Promise combinators
| Method | Resolves when | Rejects when |
|---|---|---|
| Promise.all | every promise fulfils | any one rejects (fails fast) |
| Promise.allSettled | all settle, whatever the outcome | never |
| Promise.race | the first promise settles | if the first to settle rejects |
| Promise.any | the first promise fulfils | only if all reject |
Common mistakes with Promises
- Creating a promise around code that already returns one — the "promise constructor anti-pattern".
- Using Promise.all when one failure should not discard every other result.
Node.js Promises— Interview Questions & FAQs
What is the difference between Promise.all and Promise.allSettled?+
Promise.all rejects as soon as any promise rejects, discarding the other results. allSettled waits for every promise and returns an array describing each outcome, which is what you want when partial success is useful.
