Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Node.js Tutorial

Node HOME Node Intro Node Get Started Node JS Requirements Node.js vs Browser Node Cmd Line Node V8 Engine Node Architecture Node Event Loop

Asynchronous

Node Async Node Promises Node Async/Await Node Errors Handling

Module Basics

Node Modules Node ES Modules Node NPM Node package.json Node NPM Scripts Node Manage Dep Node Publish Packages

Core Modules

HTTP Module HTTPS Module File System (fs) Path Module OS Module URL Module Events Module Stream Module Buffer Module Crypto Module Timers Module DNS Module Assert Module Util Module Readline Module

JS & TS Features

Node ES6+ Node Process Node TypeScript Node Adv. TypeScript Node Lint & Formatting

Building Applications

Node Frameworks Express.js Middleware Concept REST API Design API Authentication Node.js with Frontend

Database Integration

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit MongoDB Join

Advanced Communication

GraphQL Socket.IO WebSockets

Testing & Debugging

Node Adv. Debugging Node Testing Apps Node Test Frameworks Node Test Runner

Node.js Deployment

Node Env Variables Node Dev vs Prod Node CI/CD Node Security Node Deployment

Perfomance & Scaling

Node Logging Node Monitoring Node Performance Child Process Module Cluster Module Worker Threads

Node.js Advanced

Microservices Node WebAssembly HTTP2 Module Perf_hooks Module VM Module TLS/SSL Module Net Module Zlib Module Real-World Examples

Hardware & IoT

RasPi Get Started RasPi GPIO Introduction RasPi Blinking LED RasPi LED & Pushbutton RasPi Flowing LEDs RasPi WebSocket RasPi RGB LED WebSocket RasPi Components

Node.js Reference

Built-in Modules EventEmitter (events) Worker (cluster) Cipher (crypto) Decipher (crypto) DiffieHellman (crypto) ECDH (crypto) Hash (crypto) Hmac (crypto) Sign (crypto) Verify (crypto) Socket (dgram, net, tls) ReadStream (fs, stream) WriteStream (fs, stream) Server (http, https, net, tls) Agent (http, https) Request (http) Response (http) Message (http) Interface (readline)

Resources & Tools

Node.js Compiler Node.js Server Node.js Quiz Node.js Exercises Node.js Syllabus Node.js Study Plan Node.js Certificate

Node.js Async/Await


Introduction to Async/Await

Async/await is a modern way to handle asynchronous operations in Node.js, building on top of Promises to create even more readable code.

Introduced in Node.js 7.6 and standardized in ES2017, async/await allows you to write asynchronous code that looks and behaves more like synchronous code.

Async/await is basically Promises with a more readable syntax. This makes your code cleaner and more maintainable.

Async/await makes asynchronous code look and more feel like synchronous code. It does not block the main thread, but is easy to follow and understand.


Syntax and Usage

The syntax consists of two keywords:

  • async: Used to declare an asynchronous function that returns a Promise
  • await: Used to pause execution until a Promise is resolved, can only be used inside async functions

Example: Basic Async/Await

async function getData() {
  console.log('Starting...');
  const result = await someAsyncOperation();
  console.log(`Result: ${result}`);
  return result;
}

function someAsyncOperation() {
  return new Promise(resolve => {
    setTimeout(() => resolve('Operation completed'), 1000);
  });
}

// Call the async function
getData().then(data => console.log('Final data:', data));
Run example »

Example: Reading a File with Async/Await

const fs = require('fs').promises;

async function readFile() {
  try {
    const data = await fs.readFile('myfile.txt', 'utf8');
    console.log(data);
  } catch (error) {
    console.error('Error reading file:', error);
  }
}

readFile();
Run example »


Error Handling with Try/Catch

One of the advantages of async/await is that you can use traditional try/catch blocks for error handling, making your code more readable.

Example: Error Handling with Async/Await

async function fetchUserData() {
  try {
    const response = await fetch('https://api.example.com/users/1');
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const user = await response.json();
    console.log('User data:', user);
    return user;
  } catch (error) {
    console.error('Error fetching user data:', error);
    throw error; // Re-throw the error if needed
  }
}

You can also mix async/await with Promise .catch() for different scenarios:

// Using catch with an async function
fetchUserData().catch(error => {
  console.log('Caught outside of async function:', error.message);
});
Run example »

Running Promises in Parallel

Although async/await makes code look synchronous, sometimes you need to run operations in parallel for better performance.

Example: Sequential vs Parallel Operations

// Helper function to simulate an API call
function fetchData(id) {
  return new Promise(resolve => {
    setTimeout(() => resolve(`Data for ID ${id}`), 1000);
  });
}

// Sequential operation - takes ~3 seconds
async function fetchSequential() {
  console.time('sequential');
  const data1 = await fetchData(1);
  const data2 = await fetchData(2);
  const data3 = await fetchData(3);
  console.timeEnd('sequential');
  return [data1, data2, data3];
}

// Parallel operation - takes ~1 second
async function fetchParallel() {
  console.time('parallel');
  const results = await Promise.all([
    fetchData(1),
    fetchData(2),
    fetchData(3)
  ]);
  console.timeEnd('parallel');
  return results;
}

// Demo
async function runDemo() {
  console.log('Running sequentially...');
  const seqResults = await fetchSequential();
  console.log(seqResults);
  
  console.log('\nRunning in parallel...');
  const parResults = await fetchParallel();
  console.log(parResults);
}

runDemo();
Run example »

Async/Await vs Promises vs Callbacks

Let's see how the same task is handled with different asynchronous patterns:

With Callbacks

function getUser(userId, callback) {
  setTimeout(() => {
    callback(null, { id: userId, name: 'John' });
  }, 1000);
}

function getUserPosts(user, callback) {
  setTimeout(() => {
    callback(null, ['Post 1', 'Post 2']);
  }, 1000);
}

// Using callbacks
getUser(1, (error, user) => {
  if (error) {
    console.error(error);
    return;
  }
  console.log('User:', user);
  
  getUserPosts(user, (error, posts) => {
    if (error) {
      console.error(error);
      return;
    }
    console.log('Posts:', posts);
  });
});
Try it Yourself »

With Promises

function getUserPromise(userId) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ id: userId, name: 'John' });
    }, 1000);
  });
}

function getUserPostsPromise(user) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(['Post 1', 'Post 2']);
    }, 1000);
  });
}

// Using promises
getUserPromise(1)
  .then(user => {
    console.log('User:', user);
    return getUserPostsPromise(user);
  })
  .then(posts => {
    console.log('Posts:', posts);
  })
  .catch(error => {
    console.error(error);
  });
Try it Yourself »

With Async/Await

// Using async/await
async function getUserAndPosts() {
  try {
    const user = await getUserPromise(1);
    console.log('User:', user);
    
    const posts = await getUserPostsPromise(user);
    console.log('Posts:', posts);
  } catch (error) {
    console.error(error);
  }
}

getUserAndPosts();
Try it Yourself »
Pattern Pros Cons
Callbacks - Simple to understand
- Widely supported
- Callback hell
- Error handling is complex
- Hard to reason about
Promises - Chaining with .then()
- Better error handling
- Composable
- Still requires nesting for complex flows
- Not as readable as async/await
Async/Await - Clean, synchronous-like code
- Easy error handling with try/catch
- Easier debugging
- Requires understanding of Promises
- Easy to accidentally block execution

Best Practices

When working with async/await in Node.js, follow these best practices:

  1. Remember that async functions always return Promises
    async function myFunction() {
      return 'Hello';
    }

    // This returns a Promise that resolves to 'Hello', not the string 'Hello' directly
    const result = myFunction();
    console.log(result); // Promise { 'Hello' }

    // You need to await it or use .then()
    myFunction().then(message => console.log(message)); // Hello
  2. Use Promise.all for concurrent operations

    When operations can run in parallel, use Promise.all to improve performance.

  3. Always handle errors

    Use try/catch blocks or chain a .catch() to the async function call.

  4. Avoid mixing async/await with callbacks

    Convert callback-based functions to Promises using util.promisify or custom wrappers.

    const util = require('util');
    const fs = require('fs');

    // Convert callback-based function to Promise-based
    const readFile = util.promisify(fs.readFile);

    async function readFileContents() {
      const data = await readFile('file.txt', 'utf8');
      return data;
    }
  5. Create clean async functions

    Keep async functions focused on a single responsibility.

Best Practice: Be aware of the "top-level await" feature available in ECMAScript modules (ESM) in Node.js 14.8.0 and above, which allows using await outside of async functions at the module level.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.