我有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
处理错误的正确方法是什么?
谢谢。
答案 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);
}
}