首页 > 解决方案 > 如何处理`UnhandledPromiseRejectionWarning`

问题描述

我有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?谢谢你。

标签: javascriptnode.jserror-handlingtry-catch

解决方案


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);
  }
})();

推荐阅读