Fab*_*Zbi 9 javascript try-catch node.js promise
我的想法如下:我想同时发送多个请求,而不必等到先前执行。
所以我的伪代码如下所示:
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();Run Code Online (Sandbox Code Playgroud)
在此处运行此代码可以按预期在浏览器中运行,但会给出以下使用节点运行的输出:
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)
Run Code Online (Sandbox Code Playgroud)
知道为什么会发生这种情况吗?
请注意,我插入只是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);
}
Run Code Online (Sandbox Code Playgroud)
这将记录
[
{ status: 'rejected', reason: 'Request failed' },
{ status: 'fulfilled', value: 'Request success' }
]
done
Run Code Online (Sandbox Code Playgroud)
正如预期的那样。
| 归档时间: |
|
| 查看次数: |
7076 次 |
| 最近记录: |