2
var promises = [promise1, promise2, promise3... promiseN];

How can I use?

$.when(promise1(), promise2(), promise3(), ...promiseN()).then(function(){ doSomething()});

I rather pass the array... Any ideas how I can correctly do this? obviously this doesn't work.

 $.when(promises).then(function(){ doSomething()});

oddly done, fail, always all accept arrays.

Thanks, ~ck

Hcabnettek
  • 12,678
  • 38
  • 124
  • 190

2 Answers2

7

I am not familiar with $.when() but you should be able to do what you want using the javascript function apply(). Something along the lines of:

$.when.apply($, promises).then(function(){ doSomething()});

First param is what will be binded to "this" inside the function call (similar to what $.proxy() does in jquery), and second param is an array of parameters to pass to the function.

Eg:

myobj.myfunc.apply(myobj, [1,2,3]);
//is the same as
myobj.myfunc(1,2,3);
Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
0

I can confirm this works great for backbone fetch and jQuery $.when(). Really useful in situations like this:

fetchPromises = [];
for (key in this.dataSources) {
  source = this.dataSources[key];
  fetchPromises.push(source.fetch());
}
$.when.apply($, fetchPromises).done(this_countResults) // Do something with all the returned results
SimplGy
  • 20,079
  • 15
  • 107
  • 144