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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top