首页 > 解决方案 > 如果在通过 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 块中获取记录变量

标签: node.jspromiseasync-awaites6-promise

解决方案


因为它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
});

推荐阅读