【发布时间】:2020-08-03 01:30:56
【问题描述】:
通过使用节点 js 12.16.1 LTS 我不明白为什么这段代码会导致双重拒绝(一个未处理,一个被捕获)。 当我删除 p 承诺并在 create_bug() 中等待 p 时,它运行良好(在 try catch 块中只捕获了一个拒绝)。我不知道为什么。
Nodejs 专家,您能帮忙吗?
'use strict';
process.on('uncaughtException', (err) => {
console.error(`uncaughtException: ${JSON.stringify({name: err.name, msg: err.message})}`);
});
process.on('unhandledRejection', (err) => {
console.error(`unhandledRejection: ${JSON.stringify({name: err.name, msg: err.message})}`);
});
async function create_bug() {
console.log('In create');
let res = superCreate();
console.log(`In create, res = ${res}`);
let p = new Promise((a, r) => setTimeout(() => a(), 0));
await p;
return res;
}
async function superCreate() {
console.log('superCreate : now throwing');
throw new Error("Something wrong");
}
async function create_OK() {
console.log('In create');
let res = await superCreate();
console.log(`In create, res = ${res}`);
let p = new Promise((a, r) => setTimeout(() => a(), 0));
await p;
return res;
}
async function main() {
try {
let res = await create_bug();
console.log(`create result : ${res}`);
} catch (err) {
console.error(`ERROR caught in main : ${JSON.stringify({name: err.name, msg: err.message})}`);
}
}
main().then(() => {
setTimeout(() => console.log(`Finished`), 2000);
});
【问题讨论】:
-
问题不在于你
await p,问题在于你不awaitcreate_bug()承诺——同时做一些异步的事情。 -
create_bug 在 main 中等待。我试图指出为什么当我从 create_bug (let p = ... and await p) 中删除两行时,我没有未处理的承诺。
-
糟糕,我的意思是写
superCreate()(返回被拒绝的承诺)而不是create_bug()。