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);

新辦法: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();


免責聲明!

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



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