Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise.all 的错误捕获 #73

Open
jtwang7 opened this issue Oct 24, 2022 · 0 comments
Open

Promise.all 的错误捕获 #73

jtwang7 opened this issue Oct 24, 2022 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented Oct 24, 2022

Promise.all 的错误捕获

在开发中,大多数时间都是一个异步操作一个异步操作去执行的,但是有一些特殊情况,需要一股脑去执行多个异步操作,比如:

  • 多表单校验:只有所有表单都校验通过才能提交
  • 多接口请求:只有所有接口都请求成功才能进行下一步操作
    这时候就会用到Promise.all这个方法。

❇️ Promise.all

  • 接收一个 Promise 数组,执行结果返回一个新的 Promise
  • 所有 Promise 都成功的时候,返回的 Promise 才是成功
  • 要是有一个 Promise 失败,则返回的 Promise 是失败

Promise.all 的运行中我们发现,若 promises 中有一个请求出错的话,整体 promises 就会被中断且只会输出这个失败的状态,而忽略了其他成功的值。假如我们不希望某种错误影响到并行请求的结果输出时,就需要对 Promise.all 做一层静默处理:

✅ 方法一:在传入 promises 前,先对 promises 中的每个 promise 对象都优先捕获自身的错误,防止错误向外传播到 Promise.all 方法内。

const fun = async (promises) => {
  Promise.all(
    promises.map(promise => {
      return promise.catch(err => err)
    })
  )
    .then(res => {
      console.log('res', res)
    })
}

fun([request(1000), request(500, false)])
// res [ '成功了1000', '失败了500' ]

✅ 方法二:在ES2020中,JavaScript提供了一个新语法 Promise.allSettled,他能直接完成我们上面所做的处理
Promise.allSettled

  • 接收一个 Promise 数组,执行结果返回一个成功的 Promise
  • 返回 Promise 状态为成功
  • 返回 Promise 的值是一个数组
const fun = async (promises) => {
  Promise.allSettled(promises)
    .then(res => {
      console.log('res', res)
    })
}

fun([request(1000), request(500, false)])
// res [
//   { status: 'fulfilled', value: '成功了1000' },
//   { status: 'rejected', reason: '失败了500' }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant