![](/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.