MyInternships.in

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

Creating and consuming a promise
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

MethodResolves whenRejects when
Promise.allevery promise fulfilsany one rejects (fails fast)
Promise.allSettledall settle, whatever the outcomenever
Promise.racethe first promise settlesif the first to settle rejects
Promise.anythe first promise fulfilsonly 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.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships