Asynchronous functions are used in forEach (). What should I do if this function requires (mid), one of the properties of item, as a jsonp parameter to get data asynchronously?

RT,list contains 100 songs. Now traverse it, get the mid, of each song as the getSongvkey (jsonp) parameter to get the vkey value asynchronously, and then add vkey as an attribute to the song through the creatSong method. This vkey value needs to be used to obtain the song"s playback link.

the problem now is that the data is obtained asynchronously. When I iterate through the forEach according to the following code, I can only get how the vkey, of the last item gets its mid every time it traverses an item, and then asynchronously gets its vkey return, and then processes the next item?.

_normalizeSongs(list) {
  let ret = []
  list.forEach((item) => {
    let { musicData } = item
    if (musicData.songid && musicData.songmid && musicData.albummid) {
      getSongvkey(musicData.songmid).then(res => {
        if (res.code === ERR_OK) {
          let vkey = res.data.items[0].vkey
          ret.push(creatSong(musicData, vkey))
        }
      })
    }
  }
  return ret
}  
May.30,2021

async/await to see that this looks a lot like Synchronize. The place that encounters asynchronism will be blocked, and the asynchronous method execution will not continue until the execution of the asynchronous method is completed, which is similar to the effect of Synchronize execution. The usage of
is very simple. You can see it with a few examples from Baidu


take a chestnut, how to execute a promise callback and then go to the next

.
function P(val) {//promise 
    return new Promise((reslove) => {
        setTimeout(() => {
            reslove(val)
        }, Math.random() * 1000)
    })
}

let arr = [1, 2, 3, 4, 8];

arr.map(v => P(v)).reduce((prev, curr) => {
    return prev.then(() => curr.then((val) => {
        console.log('one by one', val)
    }))
}, Promise.resolve())

you can use the async function es6 syntax, or use the generator function. Either use promise, or unwrap


_ normalizeSongs (list) {
let ret = []
list.forEach ((item) = > {

let { musicData } = item
if (musicData.songid && musicData.songmid && musicData.albummid) {
    (function(mid){
        getSongvkey(mid).then(res => {
            if (res.code === ERR_OK) {
              let vkey = res.data.items[0].vkey
              ret.push(creatSong(musicData, vkey))
            }
            if(ret.length == list.length){
                return ret
            }
          })
    })(musicData.songmid)
}

}
}


Promise.all learn about

Menu