The Problem with async await with Lodash

I recently was writing a web scraper and ran into an issue with async await. It's not so much a problem with how it works. In fact I love the new ES2016/ES7 proposal. It's just the current tools and libraries will need to adapt to work in parallel with it. Working with Lodash with async await is just not feasible at the moment.

Fetching for a list of teams then fetching for their list of players returns a list of promises in the below example:

async function getTeams() {  
  var teamList = _.map(await getTeamList(), async (team) => {
    team.players = await getPlayerList(team.teamId);
  });

  return teamList;
}

getTeams().then((data)=> {  
  console.log('Array of promises...', data);
});

This isn't too surprising since async functions returns a promise and mapping through them simple just returns the list of them. But the problem lies in the way Lodash/Underscore implements iterating through lists. If you need to run an await, it needs to be inside an async function and cannot be inside a normal function(or arrow function for that matter). So iterating through a list and handling promises through a callback function becomes much more of an issue.

The best way I found to handle this issue to to iterate without callback functions using the old school For Loops.

async function getTeams() {  
  var teamList = await getTeamList();
  for(let i=0; i<teamList.length; i++) {
    let team = teamList[i];
    team.players = await getPlayerList(team.teamId);
  }
  return teamList;
}

getTeams().then((data)=> {  
  console.log('Array of teams with players!', data);
});
Comments powered by Disqus