博客园

super.hill

记录搬砖中遇到的坑,欢迎批评指导!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

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') })

 

 

 

posted on 2020-03-17 19:43  超岭  阅读(3805)  评论(0编辑  收藏  举报
博客园