• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Simplifying Asynchronous Programming with async/await in Node.js

  • July 4, 2023
  • CODE OF GEEKS
  • 0
async await in nodejs
async await in nodejs

Asynchronous programming is crucial in Node.js to handle concurrent operations efficiently. With the introduction of async/await in ECMAScript 2017, writing asynchronous code has become more intuitive and readable.

In this blog post, we’ll explore how async/await simplifies asynchronous programming in Node.js through code examples and practical use cases.



Understanding async and await

Async/await simplifies asynchronous programming by allowing developers to write asynchronous code that looks and feels like synchronous code. It combines the power of Promises with a cleaner syntax, making the code more readable and easier to understand.

How async functions and the await keyword work together

Async functions, marked with the async keyword, are special functions that enable the use of the await keyword. When an async function is invoked, it returns a Promise.

Within an async function, the await keyword is used to pause the execution of the function until a Promise is settled (resolved or rejected). This allows the code to wait for asynchronous operations to complete before moving on to the next line of code.

The await keyword can only be used inside an async function. It is followed by a Promise, which can be any expression that resolves to a Promise, such as a function call or a Promise object itself.

When encountering an await expression, the async function halts its execution until the Promise is resolved, and then it resumes execution, returning the resolved value.

Key benefits of using async/await over traditional callback-based or Promise-based approaches:

1. Readability: Async/await greatly improves the readability of asynchronous code by avoiding callback hell, where multiple nested callbacks can become difficult to comprehend. Async/await allows for a more linear and sequential code structure, making it easier to follow the flow of execution.

2. Error handling: With async/await, error handling becomes more straightforward. By using try/catch blocks, errors can be caught and handled in a centralized manner, providing cleaner and more readable error handling code.

3. Synchronous-like coding style: Async/await allows developers to write asynchronous code in a more synchronous-like manner, making it easier to reason about and maintain. The code appears to execute sequentially, making it more intuitive for developers to understand and debug.

4. Integration with existing code: Async/await can be used alongside existing Promise-based code. It provides a convenient way to convert callback-based functions into Promises using utility functions like util.promisify, making it easier to integrate asynchronous operations into existing codebases.

5. Debugging: Async/await provides improved debugging capabilities compared to traditional callback-based approaches. Debuggers can step through the code in a more sequential manner, allowing for easier identification and resolution of issues.



Basic Example of async/await

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function doTask() {
  console.log('Task started.');
  await wait(2000);
  console.log('Task completed.');
}

doTask();

O/P

Task started.
Task completed. (printed after 2 seconds of delay)

In this example, the wait function returns a Promise that resolves after the specified delay. The doTask function is marked as async, indicating it contains asynchronous operations. The await keyword pauses the execution of the function until the Promise returned by wait resolves. This ensures that the console logs are displayed in the expected order.

Error Handling with async/await

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const error = true;
      if (error) {
        reject('An error occurred.');
      } else {
        resolve('Data fetched successfully.');
      }
    }, 2000);
  });
}

async function handleData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

handleData();

In this example, the fetchData function returns a Promise that either resolves with the fetched data or rejects with an error message. Inside the handleData function, the await keyword is used to wait for the Promise returned by fetchData to settle. If the Promise resolves, the data is logged to the console. If the Promise rejects, the error is caught and logged using the catch block.0

Parallel Execution with async/await

function fetchUser(id) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ id, name: 'John Doe' });
    }, 2000);
  });
}

async function getUserData() {
  const user1 = fetchUser(1);
  const user2 = fetchUser(2);
  const [userData1, userData2] = await Promise.all([user1, user2]);
  console.log(userData1, userData2);
}

getUserData();

O/P

{ id: 1, name: ‘John Doe’ } { id: 2, name: ‘John Doe’ }

In this example, the fetchUser function simulates fetching user data from an API or database. The getUserData function fetches data for two users in parallel using Promise.all and awaits the combined result. The resolved user data for both users is then logged to the console.



Converting Callback-based Functions to async/await

const fs = require('fs');
const { promisify } = require('util');

const readFileAsync = promisify(fs.readFile);

async function readAndLogFile() {
  try {
    const data = await readFileAsync('path/to/file.txt', 'utf8');
    console.log('File contents:', data);
  } catch (error) {
    console.error('Error reading file:', error);
  }
}

readAndLogFile();

In this example, the readFileAsync function is created using the promisify method from the Node.js util module. This allows us to convert the callback-based fs.readFile function into a Promise-based function that can be used with async/await. The readAndLogFile function reads the contents of a file and logs them to the console, demonstrating the use of async/await with a callback-based API.

Tags: Advanced async/await usage in Node.js applicationsAsync/await patterns and techniques in Node.jsAsync/await performance considerations in Node.jsAsynchronous programming with async/await in Node.jsBest practices for using async/await in Node.jsConverting callback-based functions to async/await in Node.jsError handling with async/await in Node.jsGetting started with async/await in Node.jsHandling multiple asynchronous operations with async/await in Node.jsHow to use async/await for asynchronous operations in Node.jsImproving readability with async/await in Node.js Async/await vs. Promises in Node.jsMastering async/await in Node.jsNode.js async/await tutorialPractical examples of async/await in Node.jsSequential and parallel execution with async/await in Node.jsSimplify your Node.js code with async/awaitSimplifying asynchronous programming in Node.js with async/awaitTips and tricks for effective use of async/await in Node.jsUnderstanding the event loop in Node.js with async/await
  • Previous Introduction to Node.js: Advantages and Use Cases
  • Next Connect to MySQL Database and performing CRUD Operations using Node.js

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.