Promise.all的使用

62 阅读1分钟
  init() {
   Promise.all([promise1, promise2, promise3])
   .then(values => { console.log(values); })
   .catch(error => { console.error(error); });
  }
  
  async promise1() {
    const res = await this.rpcDo('AssetLiabilityQuery.do', {}, this)
    // console.log(res)
    return res
  },
  async promise2() {
    const res = await this.rpcDo('CreditCardListQuery.do', {}, this)
    return res
  },
  async promise3() {
    const res = await this.rpcDo('Timestamp.do', {}, this)
    return res
  },
  

在这个示例中,Promise.all() 接受了包含三个 Promise 对象的数组作为参数。当所有的 Promise 对象都解决时,then 方法会以一个包含所有 Promise 解决值的数组来调用。如果任何一个 Promise 被拒绝,则 catch 方法会以被拒绝的 Promise 的原因来调用。 如果 Promise.all() 中的任何一个 Promise 被拒绝,那么整个 Promise.all() 返回的 Promise 也会被拒绝,并且它的 catch 方法会被调用,而不会调用 then 方法。

Promise.all() 中,如果有一个 Promise 被拒绝,其他 Promise 的状态不会影响整个 Promise.all() 的结果。只要有一个 Promise 被拒绝,Promise.all() 返回的 Promise 就会被拒绝,并且它的 catch 方法会接收到被拒绝的 Promise 的原因。 所以,如果其中一个 Promise 被拒绝,成功的方法不会被调用。