【问题标题】:VanillaJS vs JQuery - wait handler until two async requests are doneVanillaJS vs JQuery - 等待处理程序直到完成两个异步请求
【发布时间】:2019-09-12 08:44:40
【问题描述】:

我已经使用 JQuery 很长时间了,我对其中的 AJAX-Calls 很熟悉。我经常遇到这样的情况,我必须等到多个请求完成后再继续处理结果。

JQuery 语法如下:

    $.when(
        $.ajax({
            type: "POST",
            url: '/Services/Service.asmx/GetResults1',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                ...
            },
            error: function (e) {
                console.log('ERROR! ' + e.responseText);
            }
        }),
        $.ajax({
            type: "POST",
            url: '/Services/Service.asmx/GetResults2',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                    ...
                });
            },
            error: function (e) {
                console.log('ERROR! ' + e.responseText);
            }
        })
    ).done(function (result1, result2) {
        // Do s.th. with result1 and result2 what is already
        // available here
        updateUI();
        ...
    });

你如何在 VanillaJS 中做到这一点?

【问题讨论】:

    标签: javascript ajax asp.net-ajax


    【解决方案1】:

    这是一个使用新的 vanilla JS fetch API 的示例

    fetch('URL', {
        method: "POST/PUT/GET/DELETE",
        body: JSON.stringify({
           name: Name,
           otherData : otherData
        }),`enter code here`
        headers: {"content-type": "application/json"}
    })
    .then(res => res.json())
    .then(response => {
        //do what you want with the response here
    })
    

    对于 GET 请求,您可以选择退出获取的正文,例如

    fetch('URL', {
        method: "GET",
        headers: {"content-type": "application/json"}
    })
    .then(res => res.json())
    .then(response => {
        //do what you want with the response here
    })
    

    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => {
          document.getElementById("userID").innerHTML = json.userId;
          document.getElementById("title").innerHTML = json.title;
          document.getElementById("completed").innerHTML= json.completed;
          })
    <div>The User ID is : </div>
        <div id="userID">
        </div>
        <div>The Title is : </div>
        <div id="title">
        </div>
        <div>Completed : </div>
        <div id="completed">
        </div>

    【讨论】:

      【解决方案2】:

      将此与您的 AJAX 请求进行比较:

      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
             receivedJSON = JSON.parse(xhttp.responseText);
             //Your success: function here...
          }else{
             //Your error: function here...
          }
      };
      xhttp.open("POST","/Services/Service.asmx/GetResults1",true);
      xhttp.send(/**Your JSON Data**/);
      

      【讨论】: