使多个回调与jQuery $ .when同步

时间:2015-02-15 13:18:24

标签: javascript jquery asynchronous synchronization jquery-deferred

这是我的示例代码:



function out(msg)
{
  $('#output').append(msg + '<br>');
}

var myDeferred = [];
$.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time)
{
  myDeferred.push($.Deferred(function(dfd)
  {
    setTimeout(function ()
    {
      out(time);
      dfd.resolve();
    }, time * 1000);
  }).promise());
});

$.when.apply($, myDeferred).then(function ()
{
  out('all is done');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
&#13;
&#13;
&#13;

此输出&#34; 1 3 4 6 7 8 9 15全部完成&#34; ,同时调用所有回调。

但我想&#34; 8 3 4 6 9 15 7 1一切都已完成&#34; ,所有回调都是一个接一个地调用。

有人可以帮助我吗?

提前致谢

2 个答案:

答案 0 :(得分:3)

问题是每个回调超时几乎同时被激活。您可以执行以下操作:

function out(msg)
{
  $('#output').append(msg + '<br>');
}

function foo(index, callback) {
  var time = array[index];
  out(time);
  if (index == array.length - 1)
    callback();
  else
    setTimeout(foo, time * 1000, index + 1, callback);
}

var array = [8, 3, 4, 6, 9, 15, 7, 1];
foo(0, function ()
{
  out('all is done');
});

使用承诺:

function out(msg)
{
  $('#output').append(msg + '<br>');
}

var myDeferred = [];
$.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time)
{
  myDeferred.push($.Deferred(function(dfd)
  {
    var f = function() {
      out(time);
      dfd.resolve();
    }
    if (index > 0)
      myDeferred[index - 1].done(function() { setTimeout(f, time * 1000); });
    else 
      setTimeout(f, time * 1000);
  }).promise());
});

$.when.apply($, myDeferred).then(function ()
{
  out('all is done');
});

答案 1 :(得分:2)

不是在初始循环中记录您的回复,而是将数据传递到resolve(),然后在when()内,您将收到已解析数据的数组。改为循环遍历该数组,所有都将按顺序

var myDeferred = [];
$.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time)
{
  myDeferred.push($.Deferred(function(dfd)
  {
    setTimeout(function ()
    {
      /* pass data to resolve()*/
      dfd.resolve(time);
    }, time * 100);
  }).promise());
});

$.when.apply($, myDeferred).then(function ()
{
    /* loop over arguments */
    $.each(arguments,function(_, time){
        out(time);
    });
    console.log(arguments);
    out('all is done');
});

DEMO