Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery数组触发问题解决得太快_Jquery_Arrays_Promise_Deferred - Fatal编程技术网

jquery数组触发问题解决得太快

jquery数组触发问题解决得太快,jquery,arrays,promise,deferred,Jquery,Arrays,Promise,Deferred,我有一个输入框的动态列表。单击按钮时,每个行项目都会发送到服务器进行处理并保存到数据库。当所有请求都返回时,进程应该调用“finish” 我从网上的各种例子中了解到: var promises=[]; $("input").each(function(){ $(promises).push( $.get("processRequest?value="+$(this).val(), function(){ $("div ##div_"+i).html("do

我有一个输入框的动态列表。单击按钮时,每个行项目都会发送到服务器进行处理并保存到数据库。当所有请求都返回时,进程应该调用“finish”

我从网上的各种例子中了解到:

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!');
}
但是当第一个get返回时,done将触发。当警报弹出窗口显示时,我仍然可以看到一些请求尚未返回


我在这里遗漏了什么?

你在推一个
。每一个
结果,而不是承诺。$。当等待一系列承诺中的每个承诺兑现时。您的情况是倒退的,请尝试:

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

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

作为旁注,带有递增数字ID的div通常表示代码设计有问题。

我的投票仅仅是因为它对ID使用了糟糕的命名约定。我的错。我把代码抄错了。我确实在每个()的内部执行push()。div实际上是将每个行项目与关联的显示输出区域绑定在一起。输入_0与div_0一起。什么会更好?我正在使用现有的解决方案,所以重新设计UI可能是不可能的,但如果我能做一些小的JQ代码更改,我会很开放的。我比较了您的代码ben,发现您使用了Promissions.push(),我使用了$(Promissions.push()。我将其改为使用裸JS数组对象,现在效果很好。谢谢OP还需要使用
$.when.apply($,promises),而不是
$.when.apply(承诺)
.apply()
需要另一个参数。尝试
$.when.apply(空,承诺)