How to do a loop with asynchronous calls in JavaScript?

时间:2019-03-17 22:34:58

标签: javascript asynchronous

I'm trying to figure out how to do a GET all with my RESTful API. What it will do is grab all of the "players" from my database with their personal info. As a traditionally synchronous minded programmer implementations like this still elude me, since the SQL query is asynchronous.

Let's say for simplicity I already have the numbers of all of the player's IDs which are a field in the database. Here is how I was thinking of it, and what I want to do in pseduocode:

 //playerIDList, contains all playerIDs as integers

 var allPlayerInfoList = [];

 for (var ID in playerIDList) {
    Execute some SQL query here, with the playerID {
      if (error) {
        skip and log error for later
      } else {
        Do a little manipulation of the returned data (i.e. formatting)
        Append the new object to our master list, allPlayerInfoList
      }
    }         
 }

 return allPlayerInfoList

I'd like to exit this loop with a list of all of the player info from my database. However, I have a feeling due to the asynchronous nature this won't work correctly. From how i understand, the for loop will execute all of the asynchronous calls, however those could take a while to process. Meaning that we could get to the end code where we want to return the allPlyaerInfoList, before all of the queries have been processed and appended to the list. How can I do this? Am I thinking about this in a reasonable manner, or should I reapproach entirely?

0 个答案:

没有答案