node.js - 如果在通过 Promise.all 处理数据时发生任何错误,则在 catch 语句中捕获单个记录
问题描述
我现在正在使用 Promise.all 处理多条记录,如果发生任何错误,我想在 catch 语句中捕获单个记录
我已经写了一个方法 callApi 现在我在主代码中调用 callApi 方法
try {
let result = await callApi(res)
}
catch (err) {
}
async function callApi(records) {
return Promise.all(
records.map(async record => {
await processRecord(record)
})
)
}
如果出现以下任何错误,我想在 catch 块中显示/捕获单个记录
try {
let result = await callApi(res)
}
catch (err) {
console.log('Got error while processing this record', record)
}
但是我将如何在 catch 块中获取记录变量
解决方案
因为它processRecord
可能会抛出,如果你希望它正在处理的记录是被捕获的,而不是实际catch
的错误、processRecord
错误和throw
记录:
function callApi(records) {
return Promise.all(
records.map(record => (
processRecord(record)
.catch((err) => {
throw record;
})
))
)
}
但是,在捕获时返回记录和错误可能很有用:
try {
let result = await callApi(res)
} catch ({ err, record }) { // <--------
console.log('Got error while processing this record', record);
console.log(err);
}
function callApi(records) {
return Promise.all(
records.map(record => (
processRecord(record)
.catch((err) => {
throw { err, record };
})
))
)
}
请注意,由于callApi
已经显式返回了 Promise,因此无需将其设为async
函数。
要等待所有请求完成,然后检查每个请求的错误,请执行以下操作:
function callApi(records) {
return Promise.all(
records.map(record => (
processRecord(record)
.then(value => ({ status: 'fulfilled', value }))
.catch(err => ({ status: 'rejected', reason: { record, err } }))
))
);
}
const result = await callApi(res);
const failures = result.filter(({ status }) => status === 'rejected');
failures.forEach(({ reason: { record, err } }) => {
// record failed for reason err
});
推荐阅读
- python - 如何在 python 中读取多个 wav 文件,并转换为 numpy 数组进行绘图
- awk - 用空格/字符替换只有一个字段的行
- java - 无法在 IntelliJ 中使用 jdk 11 编译,找不到符号
- matplotlib - 在 Windows 7 工作站上安装 Anaconda 后内联图和小部件的问题
- java - kafka 流处理器 Api 反序列化 avro 记录
- makefile - 可以在替换宏中使用makefile内部宏吗
- java-8 - 不同jdk版本的sql查询表现不同
- python - 如何从函数定义中访问内部类的常量?
- java - 枚举的 Maven 包不存在
- prometheus - 如何处理“prometheus”和“prometheus_replica”标签?