【发布时间】:2019-09-08 02:07:25
【问题描述】:
我正在阅读“for await of loop”作为described on MDN。它看起来令人印象深刻,所以我玩了一些代码,但令人惊讶的是我无法捕捉到那里抛出的错误。
'use strict';
const main = async() => {
const bar = [];
bar.push(new Promise((res) => { setTimeout(() => res(1), 1200); }));
bar.push(new Promise((res) => { setTimeout(() => res(2), 800); }));
bar.push(new Promise((res, rej) => { setTimeout(() => rej(3), 200); }));
try {
for await (const foo of bar) {
console.log('hey', foo);
}
} catch (err) {
console.error('err', err);
}
};
main();
我的输出和我预期的一样,主要是。但我不明白,为什么我会收到 UnhandledPromiseRejection?我没有发现那个错误吗?
$> node await-loop.js
(node:10704) UnhandledPromiseRejectionWarning: 3
(node:10704) 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:10704) [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.
hey 1
hey 2
err 3
(node:10704) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
有人可以帮我理解并在这里写一个正确的流行语吗?我错过了什么吗?
【问题讨论】:
标签: node.js async-await