In JavaScript how do I/should I use async/await with XMLHttpRequest?

后端 未结 4 896
不思量自难忘°
不思量自难忘° 2020-11-30 04:23

Full disclosure: I\'d qualify myself as having intermediate JavaScript knowledge. So this is slightly above my experience level at this time.

I\'ve got a Google Chro

4条回答
  •  长情又很酷
    2020-11-30 05:08

    I usually do async/await like this:

    async function doAjaxThings() {
        // await code here
        let result = await makeRequest("GET", url);
        // code below here will only execute when await makeRequest() finished loading
        console.log(result);
    }
    document.addEventListener("DOMContentLoaded", function () {
        doAjaxThings();
        // create and manipulate your DOM here. doAjaxThings() will run asynchronously and not block your DOM rendering
        document.createElement("...");
        document.getElementById("...").addEventListener(...);
    });
    

    Promisified xhr function here:

    function makeRequest(method, url) {
        return new Promise(function (resolve, reject) {
            let xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onload = function () {
                if (this.status >= 200 && this.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject({
                        status: this.status,
                        statusText: xhr.statusText
                    });
                }
            };
            xhr.onerror = function () {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            };
            xhr.send();
        });
    }
    

提交回复
热议问题