[英]Unhandled promise rejection with Promise.allSettled and try/catch
My idea is as follows: I want to send multiple requests simultaneously without having to wait until priors execution.我的想法如下:我想同时发送多个请求,而不必等到先验执行。
So my pseudo code looks as follows:所以我的伪代码如下所示:
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();
Running this code here works as intended in the browser but gives me following output running with node:在这里运行此代码可以在浏览器中按预期工作,但让我跟随 output 与节点一起运行:
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)
Any idea why this is happening?知道为什么会这样吗?
Note that I only inserted sleep
so I could test if the catch
block will be executed in case the first request fails WHICH WOULD NOT BE THE DESIRED BEHAVIOR .请注意,我只插入了
sleep
,因此我可以测试在第一个请求失败的情况下是否会执行catch
块,这不是期望的行为。 I want to initiate those requests all at the same time and I do not care if one fails.我想同时发起这些请求,我不在乎是否失败。 I want to check later with
let result = await Promise.allSettled(executions);
我想稍后检查
let result = await Promise.allSettled(executions);
which requests worked and which failed.哪些请求有效,哪些失败了。 I hope this is clear.
我希望这很清楚。
Interesting question - the problem is that you're not actually simulating async requests.有趣的问题 - 问题是您实际上并没有模拟异步请求。 In fact your two request-methods are simply creating promises which are resolved/rejected synchronously/immediately.
实际上,您的两个请求方法只是创建同步/立即解决/拒绝的承诺。 You would need to put
await
before failingRequest()
in order for the rejected promise to be caught in the surrounding try/catch
but this is probably not what you want.您需要在
failingRequest()
之前放置await
,以便被拒绝的 promise 被捕获在周围的try/catch
中,但这可能不是您想要的。
Instead you should not "start" the promises immediately, it should rather be something like:相反,您不应该立即“开始”承诺,而应该是这样的:
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);
}
This will log这将记录
[
{ status: 'rejected', reason: 'Request failed' },
{ status: 'fulfilled', value: 'Request success' }
]
done
as expected.正如预期的那样。
Any idea why this is happening?
知道为什么会这样吗?
You create the failingRequest()
and then wait 4 seconds before handling it.您创建
failingRequest()
,然后等待 4 秒再处理它。
I only inserted sleep so I could test
我只插入了睡眠,所以我可以测试
… and thereby you caused the unhandled rejection. ......因此你造成了未经处理的拒绝。 Remove the
await sleep(4000);
删除
await sleep(4000);
and it'll work as expected!它会按预期工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.