同一個js方法中兩段ajax異步請求,執行順序是怎樣的


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上,帶到下一個函數中
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM