我async await在我的 NodeJs 代码中使用,代码结构如下。
async function main(){
try {
await someFunctionThatReturnsRejectedPromise()
} catch(e) {
console.log(e)
}
}
async function someFunctionThatReturnsRejectedPromise() {
try {
await new Promise((resolve,reject) => {
setTimeout(() => {
reject('something went wrong')
}, 1000);
})
} catch(e) {
return Promise.reject(e)
} finally {
await cleanup() // remove await here and everything is fine
}
}
function cleanup() {
return new Promise(resolve => {
setTimeout(() => {
resolve('cleaup successful')
}, 1000);
})
}
main();
在 finally 块中,我正在做一些async肯定会解决的清理工作。但是这段代码正在抛出PromiseRejectionHandledWarning
(node:5710) UnhandledPromiseRejectionWarning: something went wrong
(node:5710) 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:5710) [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.
something went wrong
(node:5710) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
据我了解,我不会在这里留下任何未处理的承诺。我究竟做错了什么?应该finally按设计同步阻塞吗?如果是,为什么会这样?
更新1:
如果我转换someFunctionThatReturnsRejectedPromise为好的 ol' thenand catch,它可以正常工作:
function someFunctionThatReturnsRejectedPromise() {
return (new Promise((resolve,reject) => {
setTimeout(() => {
reject('something went wrong')
}, 1000);
})).catch(e => {
return Promise.reject(e)
}).finally(() => {
return cleanup()
})
}
更新2:(理解问题)
如果我await返回 Promise,问题就解决了。
return await Promise.reject(e)
这让我明白我做错了什么。我打破了await链条(部分与不返回Promisein then/catch语法同义)。感谢大家 :)
缥缈止盈
精慕HU
相关分类