Search code examples
jqueryajaxget

Returning an array from a function that makes a GET request using jQuery


I am trying to write a function that makes a series of get requests, stores data from each request into an array, and at the end, returns the array.

I am doing something horribly wrong because my function is returning before all the asyncrons calls have finished. I am new to javascript and not really sure how I can tell my function to hold off on returning anything until all the get requests have been processed.

function load_character_data(peopleURLArray){
  let characterData = new Object() ;
  let i = 0;
  peopleURLArray.forEach(function(url){
    $.get(url, (data) => {
      characterData[i++] = data;
    }).done(() => console.log("done"));
  });
  console.log("function returned")
  return characterData
}

OUTPUT:

function returned

done


Solution

  • your object is returning before loop completes. hence the object is empty. Try below code and check

    function load_character_data(peopleURLArray){
      let characterData = new Object() ;
      let i = 0;
      peopleURLArray.forEach(function(url){
        $.get(url, (data) => {
          characterData[i++] = data;
        }).done(() => {
    
        console.log("done")
    
        if(peopleURLArray.length == i){
            return characterData  
           }
    
        });
    
    
      });
      console.log("function returned")
    
    }