如何处理`UnhandledPromiseRejectionWarning`

时间:2019-08-02 06:15:11

标签: javascript node.js error-handling try-catch

我有await条语句,它们可能引发错误,因此我正在try/catch中执行它们。但是try/catch没有抓住它们,我得到警告:

  

(节点:4496)UnhandledPromiseRejectionWarning:错误:请求已计时   

我的代码是:

(async() => {
try
{
    const result_node = nodeClient.getInfo();

}
catch (e)
{
    console.error("Error connecting to node: " + e.stack);
}
})();

我也尝试使用wait-to-js。尽管它捕获了错误,但在stderr中仍然出现错误。

(async() => {
try
{
    const [err_node, result_node] = await to(nodeClient.getInfo());
        if(err_node)
            console.error("Could not connect to the Node");
}
catch (e)
{
    console.error("Error connecting to node: " + e.stack);
}
})();

async/await处理错误的正确方法是什么? 谢谢。

3 个答案:

答案 0 :(得分:1)

在等待异步调用返回时,需要使用await关键字。

(async() => {
  try
  {
    const result_node = await nodeClient.getInfo(); // <- await keyword before the function call
  }
  catch (e)
  {
    console.error("Error connecting to node: " + e.stack);
  }
})();

答案 1 :(得分:0)

尝试

(async() => {
   try{
       const result_node = await nodeClient.getInfo();
   }catch (e){
       console.error("Error connecting to node: " + e.stack);
   }
})();

答案 2 :(得分:0)

使用异步等待的正确过程是

var functionName = async() => {
    try
    {
        const result_node = await nodeClient.getInfo();
    }
    catch (e)
    {
        console.error("Error connecting to node: " + e);
    }
}