javascript | async-await

Async/Await in Node.js - Practical Snippets

Essential patterns and best practices for using async/await in Node.js.

Tarun Sharma
Tarun SharmaAugust 29, 2022 · 2 min read · Last Updated:

1. Basic Async/Await Usage

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

2. Sequential vs Parallel Async Calls

// Sequential
async function sequential() {
  const a = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const b = await fetch('https://jsonplaceholder.typicode.com/todos/2');
  return [await a.json(), await b.json()];
}

// Parallel
async function parallel() {
  const [a, b] = await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1'),
    fetch('https://jsonplaceholder.typicode.com/todos/2')
  ]);
  return [await a.json(), await b.json()];
}

3. Handling Errors in Async/Await

async function safeAsync(fn) {
  try {
    return [null, await fn()];
  } catch (err) {
    return [err, null];
  }
}

// Usage
// const [err, result] = await safeAsync(() => fetch(...));

4. Retrying Async Operations

async function retryAsync(fn, retries = 3, delay = 500) {
  try {
    return await fn();
  } catch (err) {
    if (retries === 0) throw err;
    await new Promise(res => setTimeout(res, delay));
    return retryAsync(fn, retries - 1, delay);
  }
}

// Usage
// await retryAsync(() => fetch(...));

5. Running Async Functions in a Loop (forEach Pitfall)

// DON'T use forEach with async/await
const arr = [1, 2, 3];
arr.forEach(async (num) => {
  await someAsyncFunc(num); // This won't wait as expected!
});

// DO use for...of
for (const num of arr) {
  await someAsyncFunc(num);
}

6. Timeout for Async/Await

async function withTimeout(promise, ms) {
  let timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Timeout')), ms)
  );
  return Promise.race([promise, timeout]);
}

// Usage
// await withTimeout(fetch(...), 1000);

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Tarun Sharma is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16