js-依次循環異步請求(普通/ES6)

要求:請求5次ajax,將結果依次顯示在頁面

老辦法:用數組+定時器代替for循環

//遞歸 -------有順序
         function getTime(j, length) {
            $start = new Date().getTime();
            Time(j, length);
        }
        function Time(j,length) {
            $.get(seturl, function (e) {
                $end = new Date().getTime();
                //js請求時間
                //計算出相差天數
                $date = $end - $start;
                $seconds = Math.ceil($date / (1000));
                $last = $seconds - e['time'];
                console.log($seconds);
                $html = $('<li>' + j + '  test1: ' + e["time"] + 's' + '   /   test2:  ' + $last + 's</li>');
                $html.appendTo($('.list'));
                //成功後,判斷是否要接着執行
                if (++j < length) {
                    getTime(j, length);
                }
                if (j == 6) {
                    //loading end
                    $('#loading').hide();
                }
            }, 'json').error(function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            })
        }
        getTime(1, 6);

模擬請求:

function time(start,length){
	console.log('遞歸第:'+start+'次');
	if(++start<=length){
	  setTimeout(function(){
		time(start,length);
	  },1000);
	  }else{
		return;
	  }
};
time(1,6);

 

新辦法:ES6 async await

    async function getTime() {
            for (var i = 1; i <6 ; i++) {
                await Time(i);
            }
        }

      function Time(j) {
            $start = new Date().getTime();
            $.get(seturl, function (e) {
                $end = new Date().getTime();
                //js請求時間
                //計算出相差天數
                $date = $end - $start;
                $seconds = Math.ceil($date / (1000));
                $last = $seconds - e['time'];
                //顯示在頁面上
                $html = $('<li>' + j + '  test1: ' + e["time"] + 's' + '   /   test2:  ' + $last + 's</li>');
                $html.appendTo($('.list'));
                if (j == 5) {
                // loading end
                $('#loading').hide();
                }
            }, 'json').error(function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            })
        }

    getTime();
```![](https://img2018.cnblogs.com/blog/1535391/201909/1535391-20190916123248980-504294697.png)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章