- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Asynchronous Functions and the Node Event Loop in Javascript
Asynchronous Functions, the programs continue to run. It does not wait! This way the waiting time of the user is reduced. Also, Javascript as a programming language itself is asynchronous.
For example, if in code we are running an expensive request, which might require a lot of time, then in case of an asynchronous function, the waiting time would be too much, and the user wouldn’t be able to perform anything else too!
Thus generally we prefer using asynchronous code when performing expensive and time-consuming operations.
Let’s take an example of Anyncronous function in javascript −
Example
console.log('One'); jQuery.get('page.html', function (data) { console.log("Two"); }); console.log('Three');
Output
One, Two, Three
Now, let’s see what is an event loop in Node.
The event loop is created inside a thread schedule in which operations our thread should be performing at any given point in time.
Any Node.js application comprises of callbacks that are executed in reaction to various events such as an incoming connection, I/O completion, timeout expiry, Promise resolution, etc. The main thread (which we now know is the Event Loop) executes all these callbacks.
When the Event loops are running, for every iteration Node checks if it is waiting for any asynchronous I/O or timers. And if nothing is found, the node shuts them down.
- Related Articles
- Understanding the Node lifecycle and event loop in node.js
- How to implement asynchronous loop in JavaScript?
- How to chain asynchronous functions in JavaScript?
- Explain asynchronous functions in JavaScript with an example
- How to pause and play a loop using event listeners in JavaScript?
- How to call multiple JavaScript functions in onclick event?
- Understanding the Event driven code execution approach in Node
- Explain Asynchronous vs Deferred JavaScript
- How does asynchronous code work in JavaScript?
- First and last child node of a specific node in JavaScript?
- Node in Javascript
- The while loop in Javascript
- Difference between regular functions and arrow functions in JavaScript
- Calling asynchronous code from index.html page in JavaScript?
- What is difference between Microtask Queue and Callback Queue in asynchronous JavaScript?
