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

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

    I create a promise for the XHR. Then simply use await inside an async function to call it.

    function getHTML(url) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'document';
            xhr.onload = function () {
                var status = xhr.status;
                if (status == 200) {
                    resolve(xhr.response.documentElement.innerHTML);
                } else {
                    reject(status);
                }
            };
            xhr.send();
        });
    }
    
    async function schemaPageHandler(){
        try {
            var parser = new window.DOMParser();
            var remoteCode = await getHTML('https://schema.org/docs/full.html');
            var sourceDoc = parser.parseFromString(remoteCode, 'text/html');
            var thingList = sourceDoc.getElementById("C.Thing");
            document.getElementById("structured-data-types").appendChild(thingList);
        } catch(error) {
            console.log("Error fetching remote HTML: ", error);
        }              
    }
    

提交回复
热议问题