Open In App
Related Articles

Asynchronous Patterns in Node.js

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 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 implementing functionality which 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:

  1. Callbacks
  2. Promises
  3. Async-await

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 the callback function contains the asynchronous operation.

The most common form is an “error-first” callback in which the parent function takes an error parameter, if there is an error then it executes the error part otherwise executes the other part.

Filename: index.js 

javascript

arr = ["Geeks", "Geeks", "pop", "Geeks"]
console.log("calling")
 
let value = arr.filter(function (element) {
    if (element != "pop")
        return element
});
 
console.log("called")
console.log(value)

                    

Run the 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 the “Pyramids of Deaths”. 

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 numbers
multiplication(5, -3).then((product) => {
    console.log("The product is:", product)
}).catch((error) => {
    console.log(error)
})

                    

Run the index.js file using the following command:  

node index.js

Output:  

The product is: 15
Only Positive number allowed

 Async-await: It is a method in which the 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 awaits 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 the index.js file using the following command:  

node index.js

Output: 

calling
GeeksforGeeks


Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads