Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>nnnnnn's right, you have to use Deferreds/promises to ensure that <code>route_data</code> is populated before sending it to the console.</p> <p>It's not immediately obvious how to do this, with particular regard to the fact that <code>$.when()</code> accepts a series of discrete arguments, not an array.</p> <p>Another issue is that any individual ajax failure should not scupper the whole enterprise. It is maybe less than obvious how to overcome this.</p> <p>I'm not 100% certain but something along the following lines should work :</p> <pre><code>$.getJSON('http://example-app/api/routes/?callback=?', function(data) { var route_promises = []; var route_data = []; function getRouteData(route) { var dfrd = $.Deferred(); $.ajax({ url: 'http://example-app/api/routes/'+route+'?callback=?', dataType: 'json' }).done(function(data) { //console.log(data); // this shows me the 13 objects route_data.push(data); }).fail(function() { route_data.push("ajax error"); }).then(function() { dfrd.resolve(); }); return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail. } $(data).each(function(i, route) { route_promises.push( getRouteData(route) ); }); //$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary. $.when.apply($, route_promises).done(function() { console.log(route_data); }); }); </code></pre> <p><em>untested</em></p> <p>See comments in code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload