Asynchronous Patterns in Node.js - GeeksforGeeks

14 Aug, 2021
Since the node is a language that runs on a single thread which in turn uses multiple threads in the background. A code in node.js should be nonblocking because if a particular line of code, for ex: Reading a large document can halt the execution of all the lines of code ahead of it which is not a good practice.That’s why to implement functionality that could take some time, is being done in an asynchronous way which takes the execution of that particular part out of the main event loop and the program runs normally.
There are three patterns of asynchronous:
CallbacksPromisesAsync-await
Callbacks
Promises
Async-await
1. Callbacks: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
This function is called when the asynchronous operation is completed. Mainly the body of callback function contains the asynchronous operation.
The most common form is “error-first” callback in which if the parent function and takes error parameter, if there is an error then it executes the error part otherwise execute the other part.
Filename: index.js 
javascript
arr = ["Geeks", "Geeks", "pop", "Geeks"]console.log("calling") var value = arr.filter(function(element) {     if(element != "pop")     return element}); console.log("called")console.log(value)
Run index.js file using the following command:  
node index.js
Output: 
calling
called
[ 'Geeks', 'Geeks', 'Geeks' ]
Generally, callbacks are not used because all the code after an asynchronous operation is nested inside a function. More asynchronous operations mean more indentation which ultimately results in unreadability and confusion and the problem becomes more and more significant by larger functions. It is also referred to as “Pyramids of deaths”. 
2. Promises: A promise is a proxy for a state or value that is unknown for the moment when the promise is created but could be determined in the near future. This lets asynchronous methods return a promise to supply value at some point in the future.
Basic Syntax: 
const promise = new Promise(function)
They have methods such as:
prototype.then()
prototype.catch() 
The .then() is used to specify what to do if the promise is fulfilled and .catch() specifies what to do if the promise is not fulfilled.
Filename: index.js 
javascript
const multiplication = (numberOne, numberTwo) => {    return new Promise((resolve, reject) => {        setTimeout(() => {             // Checking if any number is negative or not            if (numberOne < 0 || numberTwo < 0) {               // If everything is not fine              return reject("Only Positive number allowed")            }              // If everything is fine            resolve(numberOne * numberTwo)        }, 1000)    }) }  // Call for positive numbers multiplication(5, 3).then((product) => {    console.log("The product is:", product) }).catch((error) => {    console.log(error) }) // Call for negative numbersmultiplication(5, -3).then((product) => {  console.log("The product is:", product)}).catch((error) => {  console.log(error)})
Run index.js file using the following command:  
node index.js
Output:  
The product is: 15
Only Positive number allowed
3. Async-await: It is a method in which parent function is declared with the async keyword and inside it await keyword is permitted. The async and await keyword enables asynchronous, promise-based behavior so that code could be written a lot cleaner and avoid promise chains.Basic syntax: 
async function name(params) {
  const result = await waitforfunction()
} 
The async functions can contain more than one await expression. This await keyword is used to wait for the promise either to be fulfilled or rejected.
Filename: index.js 
javascript
function resolvelater() {  return new Promise(resolve => {    setTimeout(() => {      resolve('GeeksforGeeks');    }, 2000);  });} async function waitforGeeksforGeeks() {  console.log('calling');  const result = await resolvelater();  console.log(result);} waitforGeeksforGeeks()
Run index.js file using the following command:  
node index.js
Output: 
calling
GeeksforGeeks
varshagumber28
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript