0

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

1 Answer 1

1

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")

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.