0

I would like to iterate array of URLs, retrieve json data from each URL and push it as new element of my array called returned_data. Only when all json URLs have been fetched I would like to do something with returned_data.

How can I accomplish this?

Here is my lousy attempt that does not work because for loop is not allowed inside $.when:

var base_url = "http://app.loc/";

var urls = [
  base_url + "1.json",
  base_url + "2.json",
  base_url + "3.json"
];

var returned_data = [];

$.when(

  for ($i = 0; $i < urls.length; $i++) {

    $.getJSON(urls[$i], function(data) {
      returned_data.push(data);
    });

  }

).then(function() {

  console.log(returned_data);

});
Jimbotron
  • 83
  • 6

1 Answers1

0

Check the documentation: https://api.jquery.com/jquery.when/

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
    console.log( v1 ); // v1 is undefined
    console.log( v2 ); // v2 is "abc"
    console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});

d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );

You probably want to do something like

var base_url = "http://app.loc/";

var urls = [
  base_url + "1.json",
  base_url + "2.json",
  base_url + "3.json"
];
var returned_data = [];
var all = $.Deferred();

$.when(all).then(....)


  for ($i = 0; $i < urls.length; $i++) {

    $.getJSON(urls[$i], function(data) {
      returned_data.push(data);
      if (returned_data.length === urls.length) {
          all.resolve()
      }
    });

  }


Gerardo Perrucci
  • 704
  • 7
  • 13
  • If support available for `Promise.all()` it is pointelss to use `$.when` – charlietfl Jun 14 '20 at 01:21
  • @charlietfl in that case we need to create a new promise englobing the others, right? could you check my last update – Gerardo Perrucci Jun 15 '20 at 10:22
  • $.getJSON returns a promise so this is an anti-pattern... [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – charlietfl Jun 15 '20 at 21:34