javascript - 如何处理`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
?谢谢你。
解决方案
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);
}
})();
推荐阅读
- ios - 如何使用 Swift 从 Firebase 中删除数据?
- python - UrlFetchApp 不返回任何内容
- sql - 有效地从数据库中检索任何行
- android - 停止 webview 长按导航
- javascript - 如何使用我自己的 Affiliate Network 代码跟踪网站
- python - 如何在 Tkinter 的框架内显示选项菜单?
- javascript - 如何将游戏分数保存在本地存储中
- python - Python CNN 模型训练中的数据归一化
- python - Python - Notion API - 无法导入模块
- java - 使用 GenerationType.SEQUENCE 时可以为所有实体使用共享表吗?