一,兩個(或多個)js異步並發執行,怎么在兩個AJax異步操作之后執行一個新的操作 原題來自
ES6 方法
1.Promise 包裝異步ajax操作,
2.定義async 函數,
3.用await等待promise數據異步獲取完成
這一種方法簡潔高效,下面請看我專門給你寫的示例代碼
我懶得用ajax獲取數據了,就用settimeout這個函數模擬獲取數據吧,這個函數是異步的,原理效果一樣。
//模擬ajax異步操作1 function ajax1() { const p = new Promise((resolve, reject) => { setTimeout(function() { resolve('ajax 1 has be loaded!') }, 1000) }) return p } //模擬ajax異步操作2 function ajax2() { const p = new Promise((resolve, reject) => { setTimeout(function() { resolve('ajax 2 has be loaded!') }, 2000) }) return p } //等待兩個ajax異步操作執行完了后執行的方法 const myFunction = async function() { const x = await ajax1() const y = await ajax2() //等待兩個異步ajax請求同時執行完畢后打印出數據 console.log(x, y) } myFunction()
用jQ的話直接:jQuery.when()方法源碼分析
$.when($.ajax("page1"), $.ajax("page2")).done(function(){});
以及原生仿when
function ajax(callback){ callback = callback || function(){}; var xhr = new XMLHttpRequest(); xhr.open("get",""); xhr.onload = function(res){ callback(res) }; xhr.send(null); } var when = (function(){ var i = 0, len = 0, data = []; return function(array,callback){ callback = callback || function(){}; len = len || array.length; var fn = array.shift(); fn(function(res){ i++; data.push(res); if(i < len){ when(array,callback); } else { callback(data); } }); }; })(); when([ajax,ajax],function(data){ console.log(data); });
二,js多個異步請求,按順序執行next
在js里面,偶爾會遇見需要多個異步按照順序執行請求,又不想多層嵌套,,這里和promise.all的區別在於,promise或者Jquery里面的$.when 是同時發送多個請求,一起返回,發出去的順序是一起;這里是按照順序發請求
首先創建一個迭代器,接收任意多個函數參數
function nextRegister(){ var args = arguments; var count = 0; var comm = {}; function nextTime(){ count++; if(count < args.length){ if(args[count] && Object.prototype.toString.call(args[count]) == '[object Function]'){ args[count](comm,nextTime); } } } if(args[count] && Object.prototype.toString.call(args[count]) == '[object Function]'){ args[count](comm,nextTime); } }
創建多個異步的函數,注入到迭代器中
/* comm:多個函數,公用的變量 next:調用下一個函數 * */ function fn1(comm,next){ console.log('1'); comm.age = 20; next(); } function fn2(comm,next){ next(); console.log('2'); console.log(comm.age); } function fn3(comm,next){ console.log('3'); } //開始執行迭代 nextRegister(fn1,fn2,fn3);
在這里,fn1-fn3函數中,做異步操作,知道在異步成功的時候調用next()就可以繼續執行下一個函數,同時可以將前面函數返回的結果,綁定在comm上,帶到下一個函數中