Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
NodeJS Event Loop
Next article icon

Asynchronous Functions and the Node.js Event Loop

Last Updated : 14 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Asynchronous Functions

Everyone knows JavaScript is asynchronous in nature and so is the Node. The fundamental principle behind Node is that an application is executed on a single thread or process and the events are thus handled asynchronously.

If we consider any typical web server like Apache, it requires separate threads for each process until the request is satisfied. The disadvantage in using multi-thread is they are not memory intensive and doesn’t scale very well. Also, we have to ensure that each process must be thread safe and deadlock should not appear.

But Node does things differently. On starting a Node application, it creates only a single thread of execution. When the Node receives a request, it assigns the thread to that process and no other request can be processed until it has finished processing the code for the current request. Therefore, Node handles multiple requests at the same time by using event loop and callback functions. An Event Loop is a type of functionality which basically polls for specific events and invokes event handlers when required. A Callback Function is this event handler in Node.

In Node applications, the Node initiates the request but does not wait around the request to get the response. Instead of that, it attaches a callback function to the request. When the request has been completed or the response has been received by the request, the callback function emits an event to do something with either the results of the requested action or the resource requested.

If multiple people access a Node application at the same time, and the application needs to access a resource from a file, Node attaches a callback function with each request. As soon as the resource becomes available to that particular request, a callback function is called to each person’s request. The Node can handle other requests in the meantime.

The serving of the parallel requests in the Node application depends upon how busy the application is and how it is designed?

Examples:




// Normal Function
function add(a,b){
    return a+b;
}
  
// Async Function
async function asyncadd(a,b){
    Return a+b;
}
 
 

Asynchronously opening and writing the contents of a file




// load http module
var http = require('http');
var fs = require('fs');
  
// load http module
var http = require('http');
var fs = require('fs');
  
// create http server
http.createServer(function (req, res) {
  
        // open and read in helloworld.js
        fs.readFile('helloworld.js', 'utf8', function(err, data) {
  
        res.writeHead(200, {'Content-Type': 'text/plain'});
        if (err)
            res.write('Could not find or open file for reading\n');
        else
  
            // if no error, writing JS file to a client
            res.write(data);
            res.end();
            });
}).listen(8124, function() { console.log('bound to port 8124');});
  
console.log('Server running on 8124/');
 
 


Next Article
NodeJS Event Loop

M

mayank021
Improve
Article Tags :
  • Algorithms
  • DSA
Practice Tags :
  • Algorithms

Similar Reads

  • NodeJS Event Loop
    The event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It: Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network
    6 min read
  • Explain the Mechanism of event loop in Node.js
    JavaScript is a single-threaded, non-blocking, asynchronous language that uses the concept of event loop to make it work asynchronously even if it is single-threaded. Feature: The Event Loop is responsible for sending functions from the event queue to the Stack for processing when it becomes empty.
    2 min read
  • Explain the Event-Driven Architecture of NodeJS
    NodeJS uses an event-driven architecture, which is a key part of how it handles many tasks at once without blocking. This approach relies on events, event emitters, and listeners to manage asynchronous operations efficiently. Let's explore how this works. What is Event-Driven Architecture?Event-driv
    5 min read
  • Understanding Node.js Async Flows
    Node.js is a powerful runtime environment for building server-side applications. One of the key features of Node.js is its ability to handle asynchronous flows, which allows it to process multiple requests concurrently and improve the performance of web applications. Async flows in Node.js are achie
    5 min read
  • Asynchronous Programming in NodeJS
    Asynchronous programming in NodeJS allows tasks to run in the background without blocking execution, enabling efficient handling of multiple operations. It uses the event loop, callbacks, promises, and async/await to manage non-blocking I/O tasks seamlessly. Understanding Asynchronous ProgrammingAsy
    5 min read
  • What is An Event Loop in JavaScript?
    The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread. [GFGTABS] JavaScript console.log("Sta
    4 min read
  • Non-Blocking event loop in Node.js
    Node.js operates on a single-threaded, event-driven architecture that relies heavily on non-blocking I/O operations to handle concurrent requests efficiently. This approach is enabled by its event loop mechanism, which allows Node.js to handle multiple requests concurrently without creating addition
    5 min read
  • Callbacks and Events in NodeJS
    Callbacks and events are fundamental building blocks for asynchronous programming in NodeJS. They're essential for handling operations that might take some time, ensuring your application handles asynchronous operations smoothly. Callback in NodeJSIn NodeJS, Callbacks are functions passed as argumen
    3 min read
  • Explain the working of Node.js
    Welcome to the world of Node.js, an open-source runtime environment that has transformed the landscape of backend development. Traditionally, JavaScript was confined for frontend development, powering user interactions on the browser. However, with the advent of Node.js, JavaScript has broken free f
    4 min read
  • How to handle asynchronous operations in Node ?
    NodeJS, renowned for its asynchronous and event-driven architecture, offers powerful mechanisms for handling asynchronous operations efficiently. Understanding how to manage asynchronous operations is crucial for NodeJS developers to build responsive and scalable applications. What are Asynchronous
    2 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