Promise.allSettled 和 try/catch 未处理的承诺拒绝
Unhandled promise rejection with Promise.allSettled and 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);
检查哪些请求有效,哪些请求失败。我希望这是清楚的。
有趣的问题 - 问题是您实际上并没有模拟异步请求。事实上,您的两个请求方法只是在创建 resolved/rejected synchronously/immediately 的承诺。您需要将 await
放在 failingRequest()
之前,以便将被拒绝的承诺包含在周围 try/catch
中,但这可能不是您想要的。
相反,你不应该立即“启动”promise,它应该是这样的:
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
符合预期。
Any idea why this is happening?
您创建 failingRequest()
然后等待 4 秒再处理它。
I only inserted sleep so I could test
…因此您导致了未处理的拒绝。删除 await sleep(4000);
,它将按预期工作!
我的思路是这样的: 我想同时发送多个请求,而不必等到先验执行。
所以我的伪代码如下所示:
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);
检查哪些请求有效,哪些请求失败。我希望这是清楚的。
有趣的问题 - 问题是您实际上并没有模拟异步请求。事实上,您的两个请求方法只是在创建 resolved/rejected synchronously/immediately 的承诺。您需要将 await
放在 failingRequest()
之前,以便将被拒绝的承诺包含在周围 try/catch
中,但这可能不是您想要的。
相反,你不应该立即“启动”promise,它应该是这样的:
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
符合预期。
Any idea why this is happening?
您创建 failingRequest()
然后等待 4 秒再处理它。
I only inserted sleep so I could test
…因此您导致了未处理的拒绝。删除 await sleep(4000);
,它将按预期工作!