嵌套回调异步与$.Deferred异步

时间:2022-05-08 13:35:50

HTML:

<input type="button" id="btn1" value="嵌套回调异步">
<input type="button" id="btn2" value="$.Deferred异步">
<p>显示结果:<span id="result"></span></p>

JS:

var btn_1 = document.querySelector('#btn1');
var btn_2 = document.querySelector('#btn2'); btn_1.onclick = function() {
//模拟异步A
function A(callback) {
setTimeout(function() {
callback(1)
},
500)
};
//模拟异步B
function B(callback, value) {
setTimeout(function() {
callback(value + 2)
},
500)
}
//A执行完毕后,在执行B
A(function(data1) {
B(function(data2) {
document.querySelector('#result').innerHTML = "嵌套异步:" + data2;
},
data1)
})
} btn_2.onclick = function() {
//模拟异步C
function C() {
var dtd = $.Deferred(); //创建
setTimeout(function() {
dtd.resolve(3) //成功
},
500) return dtd
};
//模拟异步D
function D(value) {
var dtd = $.Deferred();
setTimeout(function() {
dtd.resolve(value + 4)
},
500) return dtd
}
//模拟异步E
function E(value) {
var dtd = $.Deferred();
setTimeout(function() {
dtd.resolve(value + 5)
},
500) return dtd
}
C().then(function(data) { //执行回调
return D(data)
}).then(function(data) {
return E(data)
}).then(function(data) {
document.querySelector('#result').innerHTML = "Deferred异步处理:" + data;
})
}

DEMO地址:http://codepen.io/jonechen/pen/EKaXxb