javascript - Pass in an array of Deferreds to $.when() -


here's contrived example of what's going on: http://jsfiddle.net/adamjford/yngcm/20/

html:

<a href="#">click me!</a> <div></div> 

javascript:

function getsomedeferredstuff() {     var deferreds = [];      var = 1;     (i = 1; <= 10; i++) {         var count = i;          deferreds.push(         $.post('/echo/html/', {             html: "<p>task #" + count + " complete.",             delay: count         }).success(function(data) {             $("div").append(data);         }));     }      return deferreds; }  $(function() {     $("a").click(function() {         var deferreds = getsomedeferredstuff();          $.when(deferreds).done(function() {             $("div").append("<p>all done!</p>");         });     }); }); 

i want "all done!" appear after of deferred tasks have completed, $.when() doesn't appear know how handle array of deferred objects. "all done!" happening first because array not deferred object, jquery goes ahead , assumes it's done.

i know 1 pass objects function $.when(deferred1, deferred2, ..., deferredx) it's unknown how many deferred objects there @ execution in actual problem i'm trying solve.

to pass array of values any function expects them separate parameters, use function.prototype.apply, in case need:

$.when.apply($, my_array).then( ___ ); 

see http://jsfiddle.net/yngcm/21/

in es6, can use ... spread operator instead:

$.when(...my_array).then( ___ ); 

in either case, since it's unlikely you'll known in advance how many formal parameters .then handler require, handler need process arguments array in order retrieve result of each promise.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -