【发布时间】:2021-08-02 18:01:36
【问题描述】:
我的想法如下: 我想同时发送多个请求,而不必等到之前的执行。
所以我的伪代码如下:
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); 检查哪些请求有效,哪些请求失败。我希望这很清楚。
【问题讨论】:
-
您更喜欢使用异步等待吗?
-
@DipakC OP 已经使用 async/await 了吗?
标签: javascript node.js promise try-catch