We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Learn More
contact@techquestworld.com
+919547614783
Premium Article
Published 8 months ago

Node.js Async vs Await Explained with Real Examples

5 min read
283 views
Node.js Async vs Await Explained with Real Examples
Photo by Techquestworld

Master async and await in Node.js with this easy guide. Includes real code examples, pros/cons and practical use cases to make your async code clean and readable.

🔹 Introduction

Handling asynchronous operations in Node.js is a must. Whether it's database access, file I/O or an API call - Node.js uses non-blocking async code.


In this blog, we'll cover:

• What is async and await?

• Why do we use them?

• Real-life examples

• Common mistakes

• Clean-up tips

🔹 What are async and await in Node.js?

async is like saying, This function might take time, like baking a cake, so let's allow it to do its thing without holding up everything else.

await tells the code to hold off and wait until it gets an answer from a promise.

🔹Real Example Without Async/Await

const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 2000);
});
};

fetchData().then((data) => {
console.log(data); // Data fetched!
});

😖 Problem?

Chaining too many .then() statements makes the code ugly and hard to manage.

🔹 Async/Await Version (Clean & Modern)

const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 2000);
});
};

const getData = async () => {
const data = await fetchData();
console.log(data); // Data fetched!
};

getData();

🔹 Use Case: API Call with Fetch

const fetch = require('node-fetch');

const getUser = async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
const user = await res.json();
console.log(user.name);
} catch (err) {
console.error('Error:', err.message);
}
};

getUser();

🔹 Common Mistakes

❌ Forgetting await → your variable is a Promise, not the data.

❌ Not using try/catch → unhandled promise rejection.

❌ Mixing then() inside async → defeats the purpose!

🔹 When to Use Async/Await

✅ When you want readable, step-by-step async code

✅ Handling API calls, database queries or file I/O

✅ Replacing long promise chains

🔹 Cleanup Tips

Here's a good pattern using finally():

const doWork = async () => {
try {
// Simulate some asynchronous task, e.g., a network request or a time-consuming operation
const result = await someAsyncFunction(); // 'await' pauses the function until 'someAsyncFunction()' resolves

// After the promise resolves, you can use the result
console.log('Work completed successfully:', result);

} catch (error) {
// If any error occurs during the async operation, it'll be caught here
console.error('An error occurred:', error);
} finally {
// This block will run no matter what, even if there's an error
console.log('Operation completed.');
}
};

Also, in real-world apps, always handle unexpected behavior using:


• process.on('unhandledRejection')

• process.on('uncaughtException')

Using async/await in Node.js makes your asynchronous code cleaner, readable and less error-prone. Ditch the messy .then() chains and make your logic easy to follow.

Author
TAPAS SAHOO

Developer by Profession, Techie by Heart

A curious mind with a love for writing and technology, dedicated to simplifying web development and programming topics while keeping up with the ever-changing tech landscape.

Discussion (0)

Replying to
Previous Article
Redux vs Zustand in 2025: Which State Manager...

Redux vs Zustand: Which One to Choose in 2025? Explore modern state management in React using Redux...

Next Article
Top 5 ES6 Tricks Most Developers Don't Know

Write modern and cleaner JavaScript with these 5 lesser-known but powerful ES6 tricks that can drast...

Related Articles

Laravel vs NodeJS in 2025: Which One Should You Learn First?
Laravel vs NodeJS in 2025: Which One Should You Le...

Laravel or NodeJS – which one should you learn in 2025? This guide helps you choose the right backen...

ExpressJS vs NestJS: Which Node.js Framework Should You Choose in 2025?
ExpressJS vs NestJS: Which Node.js Framework Shoul...

Discover the core differences between ExpressJS and NestJS. Whether you build APIs or full-scale app...

Build Your Own Cron Job Manager in Node.js | Beginner-Friendly Guide
Build Your Own Cron Job Manager in Node.js | Begin...

Learn how to create your own custom Cron Job Manager in Node.js using just one simple method. Automa...

Why Node.js Is Still the Best Backend Choice in 2025 – Performance, Scalability & Beyond
Why Node.js Is Still the Best Backend Choice in 20...

Still wondering if Node.js is the right backend tech in 2025? This article breaks down exactly why N...

Newsletter

Get the latest articles and news delivered to your inbox

Popular Tags
Trending Now