HTML: <input type="button" id="btn1" value="嵌套回調非同步"> <input type="button" id="btn2" value="$.Deferred非同步"> <p>顯示結果:<span id="result"></span></p> JS: va
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