gpt4 book ai didi

javascript - 如何处理 `UnhandledPromiseRejectionWarning`

转载 作者:行者123 更新时间:2023-12-02 23:11:49 25 4
gpt4 key购买 nike

我有 await 语句,它们可能会引发错误,因此我在 try/catch 内执行它们。但是 try/catch 没有捕获它们,我收到警告:

(node:4496) UnhandledPromiseRejectionWarning: Error: Request timed out.

我的代码是:

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

关于javascript - 如何处理 `UnhandledPromiseRejectionWarning`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com