Node.js 如何处理异步代码错误

Node.js 如何处理异步代码错误

JavaScript中的异步操作是指不会阻塞其他操作的操作。这意味着,如果我们在代码的某一点执行异步操作,则在此之后的代码会被执行,而不会等待异步操作完成。Node.js中的一个异步操作示例是当我们从Web服务器请求一些数据时。

如果我们想要处理Node.js中的异步代码错误,则可以按照以下两种方式进行。

  • 使用回调函数处理错误
  • 处理Promise拒绝

使用回调函数处理错误: 回调函数是在函数执行完成后执行某些操作的函数。我们可以在异步操作完成后调用回调函数。如果有错误,我们可以调用带有该错误的回调函数,否则我们可以调用它并将错误设置为null以及异步操作的结果作为参数。

项目设置:

步骤1: 安装Node.js(如果尚未安装)。

步骤2: 为您的项目创建一个文件夹,并在其中切换到该文件夹。在该文件夹中创建一个名为app.js的新文件。

项目结构: 按照上述步骤完成后,您的项目结构将如下所示。

Node.js 如何处理异步代码错误

在下面的代码示例中,我们使用setTimeout()方法模拟了一个异步操作。我们执行一个除法操作,1秒后返回除法的结果,如果除数为零,我们会将一个错误实例传递给回调方法。如果没有错误,我们将调用回调函数,并将错误设置为null,将除法的结果作为参数传递。错误和结果在我们的回调函数中进行处理。

app.js

const divide = (a, b, callback) => { 
  setTimeout(() => { 
    if (b == 0) { 
      callback(new Error('Division by zero error')); 
    } else { 
      callback(null, a / b); 
    } 
  }, 1000); 
}; 
  
divide(10, 2, (err, res) => { 
  if (err) { 
    console.log(err.message); 
  } else { 
    console.log(`The result of division = {res}`); 
  } 
}); 
  
divide(5, 0, (err, res) => { 
  if (err) { 
    console.log(err.message); 
  } else { 
    console.log(`The result of division ={res}`); 
  } 
});

运行应用程序的步骤: 您可以在命令行上使用以下命令来执行您的 app.js 文件。

node app.js

输出:

Node.js 如何处理异步代码错误

处理 Promise rejection(拒绝):Node.js 中,Promise 是处理异步操作的一种方式。我们可以从异步函数中返回一个 Promise,并使用 then() 方法或 async/await 来获取最后的值。当我们使用 then() 方法来消费 Promise 时,如果需要处理 Promise 的拒绝,我们可以在 then() 方法调用中添加 catch() 方法调用。Promise.catch() 是一个返回 Promise 的方法,其工作是处理被拒绝的 Promise。

语法:

// func is an async function
func().then(res => {   
    // code logic
}).catch(err => {
    // promise rejection handling logic
})

现在,如果我们想使用async/await处理Promise的拒绝,我们可以简单地使用下面给出的语法中的try/catch块来实现。

const hello = async () => {
    try {
        // func is an async function
        const res = await func();
    } catch(err) {
        // error handling logic
    }
}

在下面的示例中,我们使用setTimeout()方法模拟一个异步函数,并在一个返回Promise的异步函数中执行除法操作。如果除数为零,我们会拒绝Promise并返回一个错误,否则我们会使用除法结果解析Promise。

app.js

const divide = async (a, b) => { 
  return new Promise((resolve, reject) => { 
    setTimeout(() => { 
      if (b == 0) { 
        reject(new Error('Division by zero error')); 
      } else { 
        resolve(a / b); 
      } 
    }, 1000); 
  }); 
}; 
  
// Consuming the promise using then() method 
// and handling the rejected promise using 
// catch() method 
divide(5, 0) 
  .then((res) => { 
    console.log(`The result of division is {res}`); 
  }) 
  .catch((err) => { 
    console.log(err.message); 
  }); 
  
// This function is immedietly invoked after 
// its execution. In this case we consume the 
// promise returned by divide function() using 
// async/await and handle the error using 
// try/catch block 
(async () => { 
  try { 
    const res = await divide(10, 5); 
    console.log(`The result of division is{res}`); 
  } catch (err) { 
    console.log(err); 
  } 
})();

输出:

Node.js 如何处理异步代码错误

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程