已更新,我现在已经尝试解释我所看到的行为,但从可靠的来源获得有关该行为的答案仍然很棒unhandledRejection。我还在Reddit 上发起了一个讨论帖。为什么我会unhandledRejection在以下代码中收到一个事件(对于“error f1”)?这是出乎意料的,因为我finally在main.我在 Node (v14.13.1) 和 Chrome (v86.0.4240.75) 中看到了相同的行为:window.addEventListener("unhandledrejection", event => { console.warn(`unhandledRejection: ${event.reason.message}`);});function delay(ms) { return new Promise(r => setTimeout(r, ms));}async function f1() { await delay(100); throw new Error("error f1");}async function f2() { await delay(200); throw new Error("error f2");}async function main() { // start all at once const [p1, p2] = [f1(), f2()]; try { await p2; // do something after p2 is settled await p1; // do something after p1 is settled } finally { await p1.catch(e => console.warn(`caught on p1: ${e.message}`)); await p2.catch(e => console.warn(`caught on p2: ${e.message}`)); }}main().catch(e => console.warn(`caught on main: ${e.message}`));
添加回答
举报
0/150
提交
取消