簡體   English   中英

VanillaJS vs JQuery-等待處理程序,直到完成兩個異步請求

[英]VanillaJS vs JQuery - wait handler until two async requests are done

我已經使用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中做到這一點?

這是使用新的香草JS提取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> 

將此與您的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**/);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM