Question

i have a dynamic list of input boxes. when button is clicked, each line item is sent to server to process and save to db. when all of requests have returned, process is supposed to call the "finish".

i have this from various examples online:

var promises=[];
$("input").each(function(){
  $(promises).push(
    $.get("processRequest?value="+$(this).val(),
      function(){
        $("div ##div_"+i).html("done with input " + i);
      }
    );
  }
);

$.when.apply(promises).done(function() {
  alert('done!');
}

but the done triggers when the 1st get returns. when the alert popup shows, i can still see some of the requests still haven't returned yet.

what am i missing here?

Was it helpful?

Solution

You're pushing a .each result, rather than the promises. $.when waits for each promise in an array of promises to fulfill. Your condition is backwards, try:

 $("input").each(function(){
    promises.push($.get("processRequest?value="+this.value,
      function(){
        $("div ##div_"+i).html("done with input " + i);
      }
    )
  });

Or alternatively:

 var promises = $("input").map(function(e){ 
        return $.get("processRequest?value="+e.value,...);
 }).get();

As a side note, divs with incremental numeric IDs are usually indicative of a code design problem.

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