promise.all 出现一个失败怎么继续

133 阅读2分钟

Promise.all 是一个 JavaScript 的内置方法,用于处理多个 Promise 对象。当你在 Promise.all 中传入一个由多个 Promise 组成的数组时,它会返回一个新的 Promise 对象。这个新的 Promise 对象会在所有传入的 Promise 都成功时才会成功,或者在任何一个 Promise 失败时立即失败。

如果你希望即使某些 Promise 失败,也继续执行其他 Promise,你可以考虑以下几种方法:

1. 使用 Promise.allSettled()

Promise.allSettled() 方法会等待所有的 Promise 都已经 fulfilled 或 rejected 后才结束,并且它会返回一个包含每个 Promise 结果的对象数组。这对于处理并行操作非常有用,即使某些操作失败。

    const promises = [
      fetch('/api/data1').then((response) => response.json()),
      fetch('/api/data2').then((response) => response.json()),
      fetch('/api/data3').then((response) => response.json()),
    ]

    Promise.allSettled(promises).then((results) => {
      results.forEach((result) => {
        if (result.status === 'fulfilled') {
          console.log('成功:', result.value)
        } else {
          console.log('失败:', result.reason)
        }
      })
    })

2. 使用 Promise.all() 捕获错误并继续执行

虽然 Promise.all() 不直接支持忽略错误并继续执行,但你可以通过在 Promise.all() 中使用 .catch() 来捕获错误,并手动处理每个 Promise 的结果。

    const promises = [
      fetch('/api/data1').then((response) => response.json()),
      fetch('/api/data2').then((response) => response.json()),
      fetch('/api/data3').then((response) => response.json()),
    ]

    Promise.all(promises)
      .then((results) => {
        console.log('所有请求成功:', results)
      })
      .catch((error) => {
        console.error('至少一个请求失败:', error)
        // 这里可以继续处理其他操作,例如重试失败的请求等。
      })

3. 使用数组的 reduce 方法来手动处理每个 Promise

这种方法允许你为每个 Promise 设置独立的错误处理逻辑,从而在某个 Promise 失败时不会中断整个流程。

    const promises = [
      fetch('/api/data1')
        .then((response) => response.json())
        .catch((error) => ({ status: 'error', message: error })),
      fetch('/api/data2')
        .then((response) => response.json())
        .catch((error) => ({ status: 'error', message: error })),
      fetch('/api/data3')
        .then((response) => response.json())
        .catch((error) => ({ status: 'error', message: error })),
    ]

    promises
      .reduce((acc, promise) => {
        return acc.then(() => promise)
      }, Promise.resolve())
      .then((results) => {
        console.log('处理完成:', results)
      })
      .catch((error) => {
        console.error('处理过程中发生错误:', error)
      })