Promise.all有一点需要注意一下,当promise对象里面是普通值的时候,返回的也是普通值

class MyPromise {
  static all(array) {
    let x = new Promise((resolve, reject) => {
      let resultVal = []
      let i = 0
      function saveVal(index, value) {
        i++
        resultVal[index] = value
        if (i === array.length) {
          resolve(resultVal)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let element = array[i];
        if (element instanceof Promise) {
          element.then(res => saveVal(i, res), err => reject(err))
        } else {
          saveVal(i, element)
        }
      }

    })
    return x
  }
}

Promise.all如果有一处失败就会全盘失败,怎么解决这个问题呢?

给每一个promise数组里面的每一个promise对象进行.catch异常处理,当进行异常处理之后promise会把失败的返回值当成接下来的第二个promise的then的成功值的value里面,所以Promise.all不会走到异常里面

Last modification:April 13th, 2021 at 01:51 am
If you think my article is useful to you, please feel free to appreciate