Nodejs Promises

Node.js Tutorial

Nodejs Promises

In Nodejs Promises is an object that represents the eventual completion (or failure) of an asynchronous operation.

Promises make asynchronous code:

  • Cleaner

  • Easier to read

  • Easier to manage

  • Avoid “callback hell”


What Is a Promise?

A Promise has three states:

StateMeaning
PendingThe async operation is still running
FulfilledThe operation completed successfully
RejectedThe operation failed

Basic Promise Example


 


Using Promises with Async Functions

Node.js provides promise-based APIs (like fs.promises):

Example: Reading a file with Promises


 


Promise Chaining

You can chain multiple .then() operations:


Handling Errors in Promises

Errors are handled using .catch():


Promise.all()

Runs multiple promises at the same time and waits for all to finish.


 

Output:

["First", "Second", "Third"]

Promise.race()

Returns the result of the first completed promise:

Output:

Fast

Why Use Promises in Node.js?

✔ Avoid callback hell
✔ Better error handling
✔ Cleaner asynchronous code
✔ Works perfectly with async/await


Promises vs Callbacks

CallbacksPromises
Messy when nestedCleaner chaining
Harder to handle errorsEasy .catch()
Callback hellNo callback hell
Older patternModern approach

You may also like...