promise.allSettled和try/catch未处理的承诺拒绝



我的想法如下:我想同时发送多个请求,而不必等到执行优先级。

所以我的伪代码如下:

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function failingRequest(){
return new Promise((resolve, reject) => {
reject('Request failed');
});
}
function successRequest(){
return new Promise((resolve, reject) => {
resolve('Request success');
});
}
async function main() {
try {
let executions = [];
executions.push(failingRequest());
await sleep(4000);
executions.push(successRequest());
let result = await Promise.allSettled(executions);
console.log(result);
} catch (err) {
console.log('Outer error occured.');
console.log(err.message);
}
console.log('done');
}
main();

在这里运行这段代码可以在浏览器中正常工作,但会给我以下与节点一起运行的输出:

node:761) UnhandledPromiseRejectionWarning: Request failed
api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:761) [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 exi not handled will terminate the Node.js process with a non-zero exit code.
[
{ status: 'rejected', reason: 'Request failed' },
{ status: 'fulfilled', value: 'Request success' }
]
done
(node:761) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

知道为什么会发生这种事吗?

请注意,我只插入了sleep,这样我就可以测试在第一个请求失败的情况下是否会执行catch块。我想同时发起这些请求,我不在乎其中一个是否失败。我想稍后与let result = await Promise.allSettled(executions);核实哪些请求有效,哪些请求失败。我希望这是清楚的。

有趣的问题-问题是您实际上并没有模拟异步请求。事实上,您的两种请求方法只是创建承诺,这些承诺被同步/立即解决/拒绝。您需要将await放在failingRequest()之前,以便在周围的try/catch中捕获被拒绝的承诺,但这可能不是您想要的。

相反,你不应该";"开始";立即承诺,它应该是这样的:

try {
let executions = [];
executions.push(failingRequest);
await sleep(4000);
executions.push(successRequest);
let result = await Promise.allSettled(executions.map(promiseFn => promiseFn()));
console.log(result);
} catch (err) {
console.log('Outer error occured.');
console.log(err.message);
}

这将记录

[
{ status: 'rejected', reason: 'Request failed' },
{ status: 'fulfilled', value: 'Request success' }
]
done

正如预期的那样。

知道为什么会发生这种情况吗?

您创建failingRequest(),然后等待4秒再处理它。

我只是插入了睡眠,以便测试

,从而导致未经处理的拒绝。移除await sleep(4000);,它将按预期工作!

最新更新