1

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.

Community
  • 1
  • 1
Shanimal
  • 11,517
  • 7
  • 63
  • 76
  • 1
    `apply` is not hacky. It is good JS! – lonesomeday Jun 25 '13 at 16:12
  • @lonesomeday should I use *this* or *$* for the scope parameter and why? :) – Shanimal Jun 25 '13 at 16:39
  • 1
    It probably doesn't matter, depending on the coding of the function. But `$.when.apply($` is the equivalent to `$.when(`, so that's the safer option. – lonesomeday Jun 25 '13 at 16:41
  • 1
    IMHO, jQuery should really provide a `.whenAll()` method or allow `$.when()` to accept an array. Internally such methods would use `.apply()`, as do many other plugins. In the plugin world, an understanding of `.apply()` and `.call()` is pretty well mandatory. – Beetroot-Beetroot Jun 25 '13 at 17:54
  • garsh. the scope parameter seems to be irrelevant to the scope of done. when there is one dfd the scope of the callback is the promise returned by when. when there are multiple dfds the scope seems to be the array passed in as the second parameter to apply... http://plnkr.co/edit/CviHllLdsEEttnuRoFuX?p=preview so really `$.when.apply(whatever,...` appears to be the quiv of `$.when(...` – Shanimal Jun 25 '13 at 18:44

1 Answers1

1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375