我正在使用 async/await 处理多条记录,并使用 Promise 进行并行处理。请参阅下面的示例代码
let results = [100,200]
let promises = results.map(async record => {
try {
return await processingRecords(record);
} catch (err) {
}
});
await Promise.all(promises);
async function processingRecords(item) {
switch (item['#type']) {
case 'case1':
await Request1(item)
await Request2(item)
break
case 'case2':
await Request3(item)
}
}
但问题是,如果 Request1 出现任何错误,我无法从 Request2 调用中捕获错误,如何处理来自两个调用的错误
最佳答案
您可以在这里做一些事情来保持通话。捕获 await 语句周围的错误并返回 Request1 和 Request2 的组合结果将起作用:
例如:
async function processingRecords(item) {
switch (item['#type']) {
case 'case1':
let combinedResult = {};
try {
combinedResult.Request1Result = await Request1(item);
} catch (err) {
combinedResult.Request1Error = err;
}
try {
combinedResult.Request2Result = await Request2(item);
} catch (err) {
combinedResult.Request2Error = err;
}
// Keep the promise chain intact.;
return combinedResult;
case 'case2':
return await Request3(item);
}
}
let promises = results.map(async record => {
try {
return await processingRecords(record);
} catch (err) {
// Keep the promise chain intact by throwing err here.
throw err;
}
});
let overallResult = await Promise.all(promises);
console.log(overallResult);
关于node.js - NodeJS 中的多个 await 调用错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56738729/