0

I don't seem to understand how async/await work in the context of XMLHttpRequest(). I can write the function with callbacks and have it work in the order I expect, but when I use the following:

async function asyncLoadPartial(targetElementHandle,partial) {
        var xhr= new XMLHttpRequest();
        xhr.open('GET', partial, true);
        xhr.onreadystatechange = function(){
            if(this.readyState!==4){
                return false;
            }
            if(this.status!==200){
                return false;
            }
            //update the targetted element
            targetElementHandle.innerHTML= this.responseText;
            alert(1);
            return true;
        };
        xhr.send();
}

and call inside an async function:

async function other(){
    let dog = await asyncLoadPartial(el("mainContent"),partial);
    alert(2);
}

I get the alert "2" before alert "1" when I expected to see 1 and then 2. I read How do I return the response from an asynchronous call? and can make the example with promise/then work, but I'd still like to learn async/await.

I always used callbacks with XMLHttpRequest until more recently I use fetch, but in Cordova, the fetch API doesn't seem to be supported for pulling local files because it gives the error

Fetch API cannot load file:///android_asset/www/path. URL scheme "file" is not supported.

I could just change xhr.open('GET', partial, true); to xhr.open('GET', partial, false); and run it synchronously, but it bothers me not to know what I did wrong above.

I can get async/await to work in other contexts, but not here. Why doesn't function other() wait before moving on to the alert?

Altimus Prime
  • 2,207
  • 2
  • 27
  • 46

1 Answers1

1

That is the normal behaviour because XMLHttpRequest is not awaitable so if you notice inside of your async method there is not the keyword await so the method will run sinchronosly and the alert(2) will happend before alert(1), because alert(1) will only occur when the callback is invoked. So your usage of async and await in this context is redundant. Stick to the old callback aproach if you can't use the fetch api.