Question

I am trying to make an ajax call for each item in an array. Right now i throw all the promises into an array and then do $.when.apply...

// throw all the promises into an array
_.each(birds,function(bird,i){
    birds[i] = getBird(bird) // getBbird returns $.ajax(...)
});
// do $.when.apply
return $.when.apply($,birds).then(function(res){
    console.log("bird is the word",res)
});

My initial SO search basically confirmed I am doing this "the way" it should be done. But apply feels so hacky. Is there a more standardized/common jQuery way to achieve this?

Thanks in advance.

Was it helpful?

Solution

But apply feels so hacky. Is there a more standardized/common jQuery way to achieve this?

No, the jQuery way is hacky, and don't get me started at how the results are to be handled.

However, there is a standardised tool for this functionality that is implemented in all proper promise libraries (Bluebird, Q, RSVP, When, Dojo, and even in the upcoming ES6 promises), called all() which is available as a static function on the promise constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top