Node.js Async/Await

Node.js Tutorial

Node.js Async/Await

Async/Await is a modern way to write asynchronous code in Node.js.
It is built on top of Promises but looks and behaves like synchronous code — making it easier to read, write, and debug.


1. What is async?

A function becomes asynchronous when you add the async keyword.

Example:


 

An async function always returns a Promise.


2. What is await?

await is used inside an async function and makes JavaScript wait until a Promise is resolved or rejected.

Example:


 


Why Use Async/Await?

✔ Cleaner and more readable than Promises
✔ No callback hell
✔ Easy error handling using try...catch
✔ Looks like synchronous code


Async/Await Example with File Reading

Using fs.promises:

Async/Await With Custom Promise


Output:

Waiting...
Data received

Error Handling with Async/Await

Use try...catch for clean error handling:


 


Multiple Awaits (Sequential Execution)


 


Running Promises in Parallel

Instead of:

Use:

This runs both tasks at the same time = faster.


Rules for Async/Await

  1. await works only inside an async function

  2. Async functions always return a Promise

  3. Use try...catch to handle errors

  4. Cleanest method for asynchronous code


Async/Await vs Promises vs Callbacks

FeatureCallbacksPromisesAsync/Await
ReadabilityLowMediumHigh
Error handlingDifficultEasierVery easy
Avoids callback hell✔✔
ModernNoYesMost modern

You may also like...