Promise.allSettled returns 完成

Promise.allSettled returns catch as fullfilled

我正在使用函数 batchRequest 发出 https 请求,该函数使用 Promise.allSettled 分批收集承诺并将它们发送到 apiRequest 函数,该函数使用 axios 进行实际调用。

batchRequest 函数中,我向 HTTP 请求函数发送了一个 url 数组并等待结果。然后我使用 Promise.allSettled status 来识别 rejected 的。但是当 apiRequest 捕获为错误时 Promise.allSettled 将其视为 status: fullfilled

async function batchRequest(data, index) {
  console.log(`Running... ${index} round`)
  while (data.length) {

    // Batched request according to concurrent setting
    const batch = data
      .splice(0, settings.concurrent)
      .map((url) => apiRequest(url, index))

    const results = await Promise.allSettled(batch)

    results.forEach(({ status, value, reason }) => {
      if (status === 'fulfilled') {
        console.log(value) // I get both the try and catch here from `apiRequest`
      }
      if (status === 'rejected') {
        console.log(reason)
        // I never get anything here
      }
    })
  }
}

Api请求函数

async function apiRequest(url, index) {
  try {
    const { data } = await axios('https://api-end-point')
    return 'All good' + url
  } catch (error) {
    const status = error.response?.status ?? 'No response'
    return  `Error: ${status}, ${url}`
  }
}

不要return错误。扔了!

async function apiRequest(url, index) {
  try {
    const { data } = await axios('https://api-end-point')
    return 'All good' + url
  } catch (error) {
    const status = error.response?.status ?? 'No response'
    throw  `Error: ${status}, ${url}` // <------------change here
  }
}