-3

(Please don't mark as duplicate or at least point me to the correct answer as here I deal with multiple requests to form an array). I set up some url calls with the returned "data" values as an array. I plan to use this array to create the sum of all these values.

var data_num=[];
$.each(arr_urls, function( index, value ) {

  $.getJSON(arr_urls[index], function (data) {
      data_num.push(data);
  });
}); 
alert(data_num);
Nirs
  • 45
  • 8

2 Answers2

1

You may already be familiar with why this doesn't work, and there are excellent explanations in an oft linked duplicate. However, this isn't entirely a duplicate. Because you're not asking this:

How do I return the response from an asynchronous operation?

You're asking something more like this:

How do I loop over a bunch of asynchronous operations and wait for them all to finish?

For that, you'd first need to put them into an array. Something like this:

var my_promises = [];
var data_num = [];
$.each(arr_urls, function( index, value ) {
  my_promises.push($.getJSON(arr_urls[index], function (data) {
      data_num.push(data);
  }));
}); 

This should give you an array called promises which holds references to the currently-executing asynchronous operations. Now you just need to wait for them all to complete. Something like this:

$.when.apply($, my_promises).then(function() {
    alert(data_num);
});

This should apply the .when() function to the entire array of promises, executing the callback only when that entire array has completed.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
-1

I will assume you can't do that server side (which would be the best thing to do).

Okay, First things first: Why are you doing $.getJSON(arr_urls[index]? If you want to do use $.each, you should use value, or even better: Using a for loop

for (var i = arr_urls.length - 1; i >= 0; i--) {
     arr_urls[i]
}

Also, why don't you try doing a console.log(data) to see on the JavaScript console what is returning? Your browser console can even tell you if there was an error on the request to the sites URL.

  • Once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). – Dethariel Aug 02 '16 at 17:43
  • Sorry, i'm still very new here. Still getting the hang of it. But thanks for the links, i will take care. – Danilo Kaltner Aug 03 '16 at 01:30