1.怎樣使同一個js方法中的兩個異步請求,按順序執行
原因:默認是異步執行
解決:加入async:
false ,使其順序執行
.ajax({ url: url, type : "get",async:false, dataType:'jsonp', jsonp:"jsonpCallback", success: function(result) { //parse result , logic //logicFun(result , index ); console.log('rendering - '+index); }
2. 迭代器:
在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上,帶到下一個函數中