Promise.all 异常/出错一般情况下,all里传promise数组,但是只要有一个出错,

就会进入到catch里,不会捕获到正常数据的,所以我们要改写下,实现正常和错误的结果都能处理

function P(error = false) {
    return new Promise((res, rej) => {
        if (error) {
            rej('error')
        } else {
            res('right')
        }
    })
}
var a = P() //成功的Promise
var b = P(true) // 失败的promise

 

Promise.all(
  // promise数组,经过下面处理还是promise [a, b].map((p)
=> {
      //这里的红色字体没有什么作用,返回的依旧是成功的promise,我们优化,将他删除
return p.then(function(res) { return res }) .catch(error => error) }) ) .then(res => { console.log(res, 'res') }) .catch(error => { console.log(error, 'error') })
//这里是优化过的代码
Promise.all( [a, b].map((p)
=> { return p.catch(error => error) }) ) .then(res => { console.log(res, 'res') }) .catch(error => { console.log(error, 'error') })

 

 

 

相关文章:

  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2021-11-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2021-10-09
  • 2022-01-21
相关资源
相似解决方案