jQuery Deferred 和 Promise 用于同步和异步函数的顺序执行 [英] jQuery Deferred and Promise for sequential execution of synchronous and asynchronous functions
问题描述
如果我想以特定顺序执行同步和异步函数,我可以使用 jQuery promise,但它似乎并没有像我期望的那样工作.
If I want to have synchronous and asynchronous functions execute in a particular order I could use jQuery promise but it doesn't seem to work the way I'd expect it to work.
函数 a,b 和 c 应该在调用 deferred.resolve()
时按该顺序执行我希望函数 b 被执行,但所有函数都会立即执行,无论是否解析被调用.
Functions a,b and c should execute in that order when in a the deferred.resolve()
is called I'd expect function b to be executed but all functions are executed immediately no matter if the resolve is called.
代码如下:
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
尝试了以下修改的一些组合:
Tried a some combinations of the following modifications:
d = jQuery.Deferred();
setTimeout(function(){d.resolve();},100);
var p=d.promise();
while(++i<len){
p.then(fn[i]);
}
但是所有的结果都是一样的,在解析 a 的延迟之前 b 被调用,在解析 b 的延迟之前调用 c.
But all with same unexpected results, b gets called before deferred of a is resolved, c is called before deferred of b is resolved.
推荐答案
对于 1.8 之前的 jQuery,这是一个问题,但对于新版本的 jQuery,这不再是问题:
For jQuery prior to 1.8, this is a problem, but for new versions of jQuery, this is not a problem anymore:
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();
以下是jQuery 1.7.2的demo
Below is the demo of jQuery 1.7.2
这篇关于jQuery Deferred 和 Promise 用于同步和异步函数的顺序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!