如果我想要同步和异步函数按特定顺序执行,我可以使用jQuery Promise,但它似乎并不像我预期的那样工作。
当在a中调用deferred.resolve()
时,函数a、b和c应该按照那个顺序执行,我希望函数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的延迟解决之前被调用了。
a
函数返回一个值,该值使用b
函数等等。 - Cristiana
的返回值作为参数传递给函数b
。 - Khanh TO