What Is Callback Hell and How Can It Be Avoided

How to avoid callback hell in Node.js ?

Callback hell in Node.js is the situation in which we have complex nested callbacks. In this, each callback takes arguments that accept been obtained as a upshot of previous callbacks. This kind of callback structure leads to lesser code readability and maintainability.

Nosotros can avoid the callback hell with the help of Promises. Promises in javascript are a style to handle asynchronous operations in Node.js. It allows united states to return a value from an asynchronous part like synchronous functions. When we render something from an asynchronous method it returns a hope which can be used to consume the final value when information technology is available in the futurity with the help of then() method or await inside of async functions. The syntax to create a promise is mentioned below.

const hope = new Promise(function(resolve, decline){      // code logic });

Instance: In the code example mentioned below, we simulate an asynchronous add operation with the assist of setTimeout().

  • First, we create an add() part that takes three arguments in which two are the numbers that we desire to add and the third one is the callback part which is called with the consequence of add operations subsequently 2 seconds. Then, we calculate the result of the add-on of the first four natural numbers using a nested callback to simulate a callback hell.
  • Subsequently that, we create an addPromise() function that returns a promise and this hope is resolved after ii seconds of calling the function. Then we consume the promise using the so() method and async/await.

Javascript

const add together = function (a, b, callback) {

setTimeout(() => {

callback(a + b);

}, 2000);

};

add together(1, two, (sum1) => {

add(3, sum1, (sum2) => {

add(4, sum2, (sum3) => {

console.log(`Sum of first 4 natural

numbers using callback is ${sum3}`);

});

});

});

const addPromise = part (a, b) {

return new Hope((resolve, reject) => {

setTimeout(() => {

resolve(a + b);

}, 2000);

});

};

addPromise(1, two)

.then((sum1) => {

return addPromise(three, sum1);

})

.and then((sum2) => {

return addPromise(four, sum2);

})

.then((sum3) => {

console.log(

`Sum of first 4 natural numbers using

promise and and so() is ${sum3}`

);

});

(async () => {

const sum1 = wait addPromise(one, 2);

const sum2 = expect addPromise(iii, sum1);

const sum3 = wait addPromise(4, sum2);

panel.log(

`Sum of starting time four natural numbers using

promise and async/await is ${sum3}`

);

})();

Output:


blountsieneat1998.blogspot.com

Source: https://www.geeksforgeeks.org/how-to-avoid-callback-hell-in-node-js/

0 Response to "What Is Callback Hell and How Can It Be Avoided"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel