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

后端 未结 4 890
不思量自难忘°
不思量自难忘° 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

    You can for example create an asynchronous class to use instead of the original one. It lacks some methods but it can serve as an example.

    (function() {
        "use strict";
        
        var xhr = Symbol();
        
        class XMLHttpRequestAsync {
            constructor() {
                this[xhr] = new XMLHttpRequest();
            }
            open(method, url, username, password) {
                this[xhr].open(method, url, true, username, password);
            }
            send(data) {
                var sxhr = this[xhr];
                return new Promise(function(resolve, reject) {
                    var errorCallback;
                    var loadCallback;
                    
                    function cleanup()  {
                        sxhr.removeEventListener("load", loadCallback);
                        sxhr.removeEventListener("error", errorCallback);
                    }
                    
                    errorCallback = function(err) {
                        cleanup();
                        reject(err);
                    };
                    
                    loadCallback = function() {
                        resolve(xhr.response);
                    };
                    
                    
                    sxhr.addEventListener("load", loadCallback);
                    sxhr.addEventListener("error", errorCallback);
                    
                    
                    sxhr.addEventListener("load", function load() {
                        sxhr.removeEventListener("load", load);
                        resolve(sxhr.response);
                    });
                    sxhr.send(data);
                });
            }
            set responseType(value)
            {
                this[xhr].responseType = value;
            }
            setRequestHeader(header, value) {
                this[xhr].setRequestHeader(header, value);
            }
        }
        
        addEventListener("load", async function main() {
            removeEventListener("load", main);
    
    
            var xhra = new XMLHttpRequestAsync();
            xhra.responseType = "json";
            xhra.open("GET", "appserver/main.php/" + window.location.hash.substring(1));
            console.log(await xhra.send(null));
            
        });
        
    }());

提交回复
热议问题