문제

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