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

如果我希望以特定的顺序执行同步和异步函数,我可以使用jQuery承诺,但它似乎不像我期望的那样工作。

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

这是代码:

 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(); 

输出是:

 a b status in c: pending c done status in a: pending status in b: pending 

预期产量:

 a status in a: pending b status in b: pending c status in c: pending done 

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

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

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

对于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(); 

DEMO

下面是jQuery 1.7.2的演示

DEMO

jQuery <1.8是很好的WRT链接,你只需使用.pipe而不是.pipe 。 1.8简单地改变了。然后才变成.pipe

旁注:当您在没有数组的情况下使用它时,您不必以承诺开头。 $.when({}).then(a).then(b)就可以了。 你只需要确保你没有把时间放在里面。