zoukankan      html  css  js  c++  java
  • 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();
    

  • 相关阅读:
    1337:【例3-2】单词查找树
    1336:【例3-1】找树根和孩子
    1301:大盗阿福
    CSP-J/S 第一轮知识点选讲
    【转】C++STL各容器的操作及复杂度
    如何查看SUSE的版本信息
    野人和传教士过河问题的C语言源代码
    ubuntu如何安装软件
    Heavy Transportation POJ
    Heavy Transportation POJ
  • 原文地址:https://www.cnblogs.com/gggggggxin/p/11526694.html
Copyright © 2011-2022 走看看