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.

5
  • 1
    apply is not hacky. It is good JS! Commented Jun 25, 2013 at 16:12
  • @lonesomeday should I use this or $ for the scope parameter and why? :) Commented Jun 25, 2013 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. Commented Jun 25, 2013 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. Commented Jun 25, 2013 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... plnkr.co/edit/CviHllLdsEEttnuRoFuX?p=preview so really $.when.apply(whatever,... appears to be the quiv of $.when(... Commented Jun 25, 2013 at 18:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.