jQuery Deferred和Promise用于顺序执行同步和异步函数

HMR*_*HMR 13 javascript jquery asynchronous synchronous promise

如果我想以特定的顺序执行同步和异步函数,我可以使用jQuery promise,但它看起来并不像我期望的那样工作.

函数a,b和c应该在deferred.resolve()调用时按顺序执行我希望函数b被执行但是无论是否调用了解析,所有函数都会立即执行.

这是代码:

function a(){
  var deferred = $.Deferred();
  setTimeout(function(){
    console.log("status in a:",deferred.state());
    //this should trigger calling a or not?
    deferred.resolve("from a");
  },200);
  console.log("a");
  return deferred.promise();
};
function b(){
  var deferred = $.Deferred();
  setTimeout(function(){
    console.log("status in b:",deferred.state());
    deferred.resolve("from b");
  },200);
  console.log("b");
  return deferred.promise();
}
//synchronous function
function c(){
  var deferred = $.Deferred();
  console.log("c");
  console.log("status in c:",deferred.state());
  deferred.resolve("from c");
  return deferred.promise();
}
function test(){
  fn=[a,b,c],i=-1,
  len = fn.length,d,
  d = jQuery.Deferred(),
  p=d.promise();
  while(++i<len){
    p=p.then(fn[i]);
  }
  p.then(function(){
    console.log("done");
  },
  function(){
    console.log("Failed");
  });
  d.resolve();
  //instead of the loop doing the following has the same output
  //p.then(a).then(b).then(c);
  //d.resolve();
}
test();
Run Code Online (Sandbox Code Playgroud)

输出是:

a
b
status in c: pending
c
done
status in a: pending
status in b: pending
Run Code Online (Sandbox Code Playgroud)

预期产量:

a
status in a: pending
b
status in b: pending
c
status in c: pending
done
Run Code Online (Sandbox Code Playgroud)

尝试了以下修改的一些组合:

  d = jQuery.Deferred();
  setTimeout(function(){d.resolve();},100);
  var p=d.promise();
  while(++i<len){
    p.then(fn[i]);
  }
Run Code Online (Sandbox Code Playgroud)

但是所有具有相同意外结果的b都会在延迟a被解析之前被调用,c被调用之前被调用b.

Kha*_* TO 9

对于1.8之前的jQuery,这是一个问题,但对于新版本的jQuery,这不再是一个问题:

function test(){
  var d = jQuery.Deferred(), 
  p=d.promise();
  //You can chain jQuery promises using .then
  p.then(a).then(b).then(c);
  d.resolve();
}
test();
Run Code Online (Sandbox Code Playgroud)

DEMO

下面是jQuery 1.7.2的演示

DEMO