以下代码为p2提供了UnhandledPromiseRejectionWarning,尽管已明确处理了p2的错误。
function syncFunctionReturnsPromise(val)
{
return new Promise((r,x)=> {
setTimeout(()=> {
if (val) {
r('ok');
} else {
x('not ok');
}
}, val?1000:500);
});
}
async function test(){
let p1 = syncFunctionReturnsPromise(true);
let p2 = syncFunctionReturnsPromise(false);
await p1.catch(ex => console.warn('warning:', ex)); //errors in these 2 promises
await p2.catch(ex => console.warn('warning:', ex)); //are not the end of the world
console.log('doOtherStuff');
}
test();
输出看起来像这样:
(node:9056) UnhandledPromiseRejectionWarning: not ok
(node:9056) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9056) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
warning: not ok
doOtherStuff
(node:9056) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
对于我为什么不应该立即如此
答案 0 :(得分:1)
这是因为第一次等待是在处理程序附加到p2之前同步等待。但是p2在p1完成之前会失败。
因此节点检测到p2失败,没有任何错误处理。
在更高版本的节点中,这可能会导致程序终止,而不仅仅是警告。
解决方法是在等待之前附加处理程序
async function test(){
let p1 = syncFunctionReturnsPromise(true);
let p2 = syncFunctionReturnsPromise(false);
p1 = p1.catch(ex => console.warn('warning:', ex)); //errors in these 2 promises
p2 = p2.catch(ex => console.warn('warning:', ex)); //are not the end of the world
await p1;
await p2;
console.log('doOtherStuff');
}
很明显,您可以在声明中内联它,尽管在我的真实世界代码中,它整齐地作为单独的行。
答案 1 :(得分:0)
这是另一种方式:
malloc