Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Async Await in Node.js
Next article icon

Async Await in Node.js

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Async and await in Node are the modern way of handling asynchronous operations more efficiently. These are powerful keywords that replaces the traditional callback and Promise chaining approaches.

Handling Asynchronous Operations Before Async Await

Callbacks

Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed.

Example of a Callback:

app.get('/', function(){
function1(arg1, function(){
...
})
});

The problem with this kind of code is that this kind of situations can cause a lot of trouble and the code can get messy when there are several functions. This situation is called what is commonly known as a callback hell. So, to find a way out, the idea of Promises and function chaining was introduced.

Promises

Example: Before async/await

function fun1(req, res){
return request.get('http://localhost:3000')
.catch((err) =>{
console.log('found error');
}).then((res) =>{
console.log('get request returned.');
});

Explanation: The above code demos a function implemented with function chaining instead of callbacks. It can be observed that the code is now more easy to understand and readable. The code basically says that GET localhost:3000, catch the error if there is any, if there is no error then implement the following statementconsole.log('get request returned.'); With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining.

Async/await syntax makes handling asynchronous operations in Node.js much simpler.

Async Await

Async Await are the modern tools in node for handling async operations providing better redability to the code. This functions with async keyword automatically returns a promise.

The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise. The code now looks like below.

Example: After async/await

async function fun1(req, res){
let response = await request.get('http://localhost:3000');
if (response.err) { console.log('error');}
else { console.log('fetched response');
}

Explanation: The code above basically asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.

Code writing and understanding becomes easy with async/await as can be observed from both the examples.

How Async/ Await works?

Define an async function which means use the async keyword before the function definition. This functional implecitly returns a promise.

async fun(){
//...
}

Then use the await keyword before the function returning a promise, it pauses the execution untill the promise is respolved

async fun(){
let response = await fetchData();
return response;
}

Summary

Async await are the modern way of handling asynchronous operations. They act as the syntactic sugar for the promises providing synchronous like syntax. It helps to write clean and maintainable code.


Next Article
Async Await in Node.js

P

Parikshit Hooda
Improve
Article Tags :
  • Technical Scripter
  • Web Technologies
  • Node.js

Similar Reads

    Async Hooks in Node.js
    Async_hooks module is used because it provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application. Features: You can capture any asynchronous activity in a Node.js process.Minimal performance overhead.Powerful and flexible API. These res
    2 min read
    Explain Async Await with Promises in Node.js
    Async/Await in Node.js is a powerful way to handle asynchronous operations. It allows you to write asynchronous code in a synchronous manner, making it easier to read, write, and debug. This feature is built on top of Promises, which represent a value that may be available now, or in the future, or
    4 min read
    Async and Await in JavaScript
    Async and Await in JavaScript are used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows.JavaScriptasync function fetchData() { const response = await
    3 min read
    File handling in Node.js
    The most important functionalities provided by programming languages are Reading and Writing files from computers. Node.js provides the functionality to read and write files from the computer. Reading and Writing the file in Node.js is done by using one of the coolest Node.js modules called fs modul
    4 min read
    How to use Async-Await pattern in example in Node.js ?
    Modern javascript brings with it the async-await feature which enables developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write.
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences