jQuery Deferred和Promise用于同步和异步函数的顺序执行
jQuery Deferred and Promise for sequential execution of synchronous and asynchronous functions
如果我想让同步和异步函数按特定顺序执行,我可以使用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的deferred被解析之前被调用,c在b的deferrd被解析之前调用。
对于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();
演示
下面是jQuery 1.7.2 的演示
演示
jQuery<1.8是很好的WRT链接,您只需要使用.pipe
而不是.then
。1.8简单地将CCD_ 4改变为CCD_。
旁注:当您在没有数组的情况下使用它时,您不必从promise开始。$.when({}).then(a).then(b)
会很好地发挥作用。你只需要确保你没有把a
放在when
里面。
相关文章:
- javascript函数和代码隐藏函数的执行顺序
- 使函数按顺序运行[Node JS]
- AngularJS:如何按照预定义的顺序执行函数
- 按顺序执行导入的 Javascript 函数
- $http.post() angularjs 响应函数未按正确的顺序执行
- 如何按顺序执行 jQuery 函数
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 如何按顺序调用延迟函数
- 使用promise或setTimeout确定延迟函数的调用顺序
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 我如何向这个脚本添加一个点击按钮循环URL函数(按给定顺序在URL之间切换),或者这可能吗
- AngularJS -控制器函数顺序-一些引用不起作用
- 我如何激活3个不同的函数顺序在javascript
- jQuery JavaScript函数顺序
- JavaScript函数顺序:为什么重要?
- Javascript函数顺序
- Javascript函数顺序
- node.js中的函数顺序
- Javascript函数顺序
- JavaScript:执行函数顺序 - 在函数完成处理之前嵌套函数返回值