閉包應用之:異步變同步

問題思考

在不使用ES6的前提下如何將一個多個異步請求按順序執行呢?
好比:數組

var imgUrls = [
     'http://www.xxx.com/1.jpg',
     'http://www.xxx.com/2.jpg',
     'http://www.xxx.com/3.jpg',
     'http://www.xxx.com/4.jpg',
     'http://www.xxx.com/5.jpg'
 ];
 要求使用JavaScript代碼按順序依次請求這5張圖片,一次只能請求一張

解決思路

能夠結合 閉包+回調+遞歸 組合來解決閉包

var imgUrls = [
       'http://www.xxx.com/1.jpg',
       'http://www.xxx.com/2.jpg',
       'http://www.xxx.com/3.jpg',
       'http://www.xxx.com/4.jpg',
       'http://www.xxx.com/5.jpg'
   ];
   // 請求圖片
   function getImg(url, cb){
       var img = new Image();
       img.onload = function(){
           if(typeof cb === 'function'){
               cb();
           }
       }
       img.src = url;
   }

   ;(function iterator(index){
       // 當index等於imgUrls數組的長度的時候就再也不執行,不然會形成死循環
       if(index === imgUrls.length){
           return;
       }
       getImg(imgUrls[index], function(){
           iterator(index + 1);
       })
   })(0);
相關文章
相關標籤/搜索