无法使用async / await停止函数提前返回

时间:2018-04-02 19:53:39

标签: javascript

我正在尝试使用async / await来调用API并在迭代多级对象/数组并提取相关数据之前等待结果。我遇到的问题是我无法访问forLoop之外的数据。见下文:

const gameStrings = ['LAA-NYM', 'LAA-TB', 'NYY-HOU'];

const startingPlayers = [];

gameStrings.forEach(async function(element, i) {

let query = await fetch('fakeapi.com', element);

  query.gamestartinglineup.teamLineup.forEach(b => b.actual.starter.forEach(c => {

    if (c.player) {
      const player = {
        id: c.player.FirstName + '-' + c.player.LastName + '-' + c.player.ID
      }
      startingPlayers.push(player);
    }

  }));
  

startingPlayers ['Mookie-Betts-10456','...','...']< - 在forEach中,数据就在这里!

})
  

startingPlayers []< - 在forEach之外,它是一个空数组......

1 个答案:

答案 0 :(得分:1)

使用for(let i of items){...

时,请使用.forEach(t => {...代替async循环
const gameStrings = ['LAA-NYM', 'LAA-TB', 'NYY-HOU'];

const startingPlayers = [];

for (let element of gameStrings) {

    let query = await fetch('fakeapi.com', element);

    query.gamestartinglineup.teamLineup.forEach(b => b.actual.starter.forEach(c => {

        if (c.player) {
            const player = {
                id: c.player.FirstName + '-' + c.player.LastName + '-' + c.player.ID
            }
            startingPlayers.push(player);
        }

    }));
}