Promise.all的理解和使用

107 阅读1分钟

Promise.all的理解和使用

1、什么是Promise.all

Promise.all可以将多个Promise实例包装成一个新的Promise实例,Promse.all在处理多个异步处理时非常有用,比如说一个页面上需要等两个或多个ajax的数据回来以后才正常显示,在此之前只显示loading图标。

2、Promise.all的使用;

业务场景:多个数据请求成功后进行业务的处理

1)、业务接口,此时p_no为不同的值;

   async queryVideo(p_no: any) {
    const resp = await this.$service.q_vt_res({ cn: config.cn!, pn: config.pn!, p_no: p_no })
    return resp
  }

2、Prommis.all接受数组,因此需要把业务接口封装成一个数组,this.ailist为业务返回数组;

    this.ailist.forEach((id: any) => {
        this.id.push(this.queryVideo(id.p_no))
      })

此时this.id为数组;

3、发起Prommis.all的请求,返回的values也是一个数组,可以进行业务逻辑处理;

   Promise.all(this.id).then((values) => {
        values.forEach((item: any) => {
          this.videolist.push(item.rings)
        })
      }).catch((error)=>{
      console.log(error)
      })
     ```