📜  如何避免 Node.js 中的回调地狱?

📅  最后修改于: 2022-05-13 01:56:48.379000             🧑  作者: Mango

如何避免 Node.js 中的回调地狱?

Node.js 中的回调地狱是我们有复杂的嵌套回调的情况。在这种情况下,每个回调都接受作为先前回调的结果而获得的参数。这种回调结构导致代码可读性和可维护性较差。

我们可以在 Promises 的帮助下避免回调地狱。 javascript 中的 Promise 是在 Node.js 中处理异步操作的一种方式。它允许我们从异步函数(如同步函数)返回一个值。当我们从异步方法返回某些东西时,它会返回一个 Promise,当它在未来可用时,它可用于在 then() 方法或异步函数内部的 await 的帮助下使用最终值。下面提到了创建 Promise 的语法。

const promise = new Promise(function(resolve, reject){
     // code logic
});

示例:在下面提到的代码示例中,我们借助 setTimeout() 模拟了一个异步添加操作。

  • 首先,我们创建一个 add()函数,它接受三个参数,其中两个是我们要添加的数字,第三个是回调函数,它在 2 秒后调用 add 操作的结果。然后,我们使用嵌套回调计算前四个自然数相加的结果,以模拟回调地狱。
  • 之后,我们创建一个 addPromise()函数,该函数返回一个 Promise,并且该 Promise 在调用该函数两秒后被解析。然后我们使用 then() 方法和 async/await 来使用 promise。
Javascript
// The callback function for function
// is executed after two seconds with
// the result of addition
const add = function (a, b, callback) {
  setTimeout(() => {
    callback(a + b);
  }, 2000);
};
  
// Using nested callbacks to calculate
// the sum of first four natural numbers.
add(1, 2, (sum1) => {
  add(3, sum1, (sum2) => {
    add(4, sum2, (sum3) => {
      console.log(`Sum of first 4 natural 
      numbers using callback is ${sum3}`);
    });
  });
});
  
// This function returns a promise
// that will later be consumed to get
// the result of addition
const addPromise = function (a, b) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(a + b);
    }, 2000);
  });
};
  
// Consuming promises with the chaining of then()
// method and calculating the result
addPromise(1, 2)
  .then((sum1) => {
    return addPromise(3, sum1);
  })
  .then((sum2) => {
    return addPromise(4, sum2);
  })
  .then((sum3) => {
    console.log(
      `Sum of first 4 natural numbers using 
       promise and then() is ${sum3}`
    );
  });
  
// Calculation the result of addition by
// consuming the promise using async/await
(async () => {
  const sum1 = await addPromise(1, 2);
  const sum2 = await addPromise(3, sum1);
  const sum3 = await addPromise(4, sum2);
  
  console.log(
    `Sum of first 4 natural numbers using 
     promise and async/await is ${sum3}`
  );
})();


输出: