当前位置:网站首页>Async await used in map

Async await used in map

2022-07-04 22:55:00 Chirp bit

Preface

When practicing wechat applet , You need to traverse the elements in the array , Get the id And send a request to request the corresponding resource . This requires that map Loop traversal and async await Combine . Because of asynchronous operation ,async The function returns a promise object , be map Traversal returns a promise An array of objects , We need to wait until we get all promise After that, follow-up operations .

Promise.all

Promise.all Multiple Promise The example is packaged into a new Promise example . meanwhile , Success and failure return values are different , Success returns an array of results , And when they fail, they return to be the first reject Value of failure state .

And map combination

The general pattern of asynchrony map yes Promise.all(arr.map(async (...) => ...)).
example ( Application of wechat applet )

    let videos = video.datas.map(async item =>{
    
      item.id = index++; 
      item.videoUrl = await this.getVideoUrl(item.data.vid)
      return item
    })
   let temp = await Promise.all(videos)
    this.setData({
    
      video:temp
    })
原网站

版权声明
本文为[Chirp bit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041951524575.html