我正在努力解决我面临的有关异步/等待和 Promises 的问题。我设法将我的问题归结为以下代码:
async function sleep(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function fetchMock(): Promise<any> {
return new Promise(() => {
throw 'error fetching result';
});
}
async function main(): Promise<any> {
const kickedOffRequest = fetchMock();
await sleep(10);
return kickedOffRequest;
}
main()
.then(() => console.log('resolved promise!'))
.catch(error => console.error('caught error!', error));
我收到以下警告:
(node:82245) UnhandledPromiseRejectionWarning: error fetching result
(node:82245) 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:82245) [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.
caught error! error fetching result
(node:82245) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
您可以 在此沙箱 中观察到相同的问题。我注意到注释掉 await sleep(10)
解决了这个问题,但我对承诺的了解显然比我想象的要少。为什么注释该行会使我的程序运行?我很想问如何修复 Promise rejection was handled asynchronously
错误,但我希望一旦我理解了 await sleep(10)
是如何导致我得到的错误的,我将能够自己修复这个错误.
提前感谢您花时间阅读/回答这个问题!
原文由 marhaupe 发布,翻译遵循 CC BY-SA 4.0 许可协议
node.js 中未处理拒绝的检测不完善。在被拒绝的 promise 的生命周期中有特定的点,引擎会检查是否有处理程序,并且它并不总是等到最后可能的时刻,所以它可能会错过您添加处理程序的地方。在您的特定情况下,您可能需要在本地附加一个
.catch()
处理程序,然后完成您想要完成的工作,然后重新抛出错误。此解决方法对您有效,同时仍然保持所需的解析/拒绝来自main()
(例如,不将接口更改为 main)。所以,这不是特别漂亮,但它符合我们在评论中谈到的规范。
main()
调用fetchMock()
fetchMock()
开始的延迟时间已经过去。fetchMock()
解决或拒绝的自定义延迟时间更长,则不会添加进一步的延迟。fetchMock()
main()
返回的承诺,以相同的原因或价值被拒绝或解决。关键要素是它在调用
fetchMock()
之前捕获时间,然后在fetchMock()
解决或拒绝时,它决定是否在传递解决/拒绝值之前再延迟时间/通过的原因。Note, also that
sleep()
andfetchMock()
already directly return promises and don’t useawait
so there is no requirement for them to beasync
。