问题是;当我们网页需要与后台进行局部交换数据,我们使用ajax,例如;
var settings = {"async" : true,
"crossDomain" : true,
"url" : "suityourself",
"method" : "POST",
"datatype" : "json",
"headers" : {
"content-type" : "application/x-www-form-urlencoded"
},
data : {
"email" : "1234567890@qq.com"
},
error : function(XMLHttpRequest, data, object) {
console.log("XMLHttpRequest " + XMLHttpRequest.status + " error "
+ data + " object " + object);
alert("server is wrong");
},
success : function(response) {
console.log(response);
}
};
$.ajax(settings);
这是ajax普遍的做法
现在假设我们有三个方法,三个参数
var p1,p2,p3;
function runAsync1(p1) {
var def = $.Deferred();
//做一些异步操作
setTimeout(function() {
console.log(' 1 执行完成');
def.resolve(' 1 随便什么数据');
}, 2000);
return def.promise();
}
function runAsync2(p2) {
var def = $.Deferred();
//做一些异步操作
setTimeout(function() {
console.log(' 2 执行完成');
def.resolve(' 2 随便什么数据');
}, 2000);
return def.promise();
}
function runAsync3(p3) {
var def = $.Deferred();
//做一些异步操作
setTimeout(function() {
console.log(' 3 执行完成');
def.resolve(' 3 随便什么数据');
}, 2000);
return def.promise();
}
要求是;runAsync1执行完毕,runAsync2执行,runAsync2执行完毕,runAsync3执行。并且p1是runAsync1的参数,runAsync1返回结果是runAsync2的参数
runAsync2返回结果是runAsync3的参数。
可能直观上是说在runAsync1中调用runAsync2并传参,runAsync2中调用runAsync3并传参。这样形成一个方法调用串。
现在有了promise则可以不这么做,例如
$.when(runAsync1(p1)).then(successfunction,failurefunction);
$.when(runAsync1())
.then(function(){
$.when(runAsync2()).then(function(){
$.when(runAsync3()).then(function(){
console.log("全部完成");
},function(){
});
},function(){
});
},function(){
});
这样即可异步串行了。其实这样等价于方法嵌套调用。下面是另一种用法,但是无法达到效果
$.when(runAsync1(),runAsync2(),runAsync3()).then(function(){
三个方法异步完成,但是无法将runAsync1()的返回传递给runAsync2(),runAsync2()的返回传递给runAsync3()
},function(){
有一个方法失败,则都会失败。
});