目的:使多個ajax進程能有序的執行,而不是異步同時執行
第一步:給第一個ajax所在的函數(Ajax1)傳遞一個success參數(函數),當ajax執行完之後,調用success()函數。
第二步:如果後面還有要順序執行的異步程序,可以參照第一步。
第三步:new Promise(Ajax1()).then(Ajax2);
第四步:如果有多個ajax(異步)需要順序執行,
new Promise(Ajax1).then(function(){
return new Promise(Ajax2);
}).then(function(){
return new Promise(Ajax3);
}).then(Ajax4);
over:這樣就完成了異步的進程完成順序執行的要求
事例:異步使用setTimeout代替
function func1(success){
setTimeout(function(){
console.log("func1");
success();
},1000)
}
function func2(success){
setTimeout(function(){
console.log("func2");
success();
},1000)
}
function func3(success){
setTimeout(function(){
console.log("func3");
success();
},1000)
}
function func4(){
setTimeout(function(){
console.log("func4");
},1000)
}
new Promise(func1).then(function(){
return new Promise(func2);
}).then(function(){
return new Promise(func3);
}).then(func4);
擴展Promise.all:有三個異步必須都執行完後,才能執行第四個異步
Promise.all( [new Promise(func1), new Promise(func2), new Promise(func3)]).then(func4);
擴展:promise.race():三個異步中有一個執行完之後就執行第四個
Promise.race( [new Promise(func1), new Promise(func2), new Promise(func3)]).then(func4);