![](/img/trans.png)
[英]How do I handle the UnhandledPromiseRejectionWarning in Node.JS
[英]How to handle `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);
}
})();
尝试这个
(async() => {
try{
const result_node = await nodeClient.getInfo();
}catch (e){
console.error("Error connecting to node: " + e.stack);
}
})();
使用异步等待的正确过程是
var functionName = async() => {
try
{
const result_node = await nodeClient.getInfo();
}
catch (e)
{
console.error("Error connecting to node: " + e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.