Search code examples
javascriptxmlhttprequestfetch-api

How to convert fetch() to XML HTTP Requests?


I have some (copy-pasted) code that uses fetch(). However, in my use case, XMLHttpRequest() makes more sense than fetch(), but I am not able to convert the code so that it uses XMLHttpRequests.

This is my fetch() code:

fetch("file.wasm")
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes,importObject))
    .then(results => callback(results.instance.exports));

I tried rewriting it to:

var x;
if(window.XMLHttpRequest)x=new XMLHttpRequest();
else x=new ActiveXObject("Microsoft.XMLHTTP");

x.onreadystatechange=function(){
    if(this.readyState!==4)return;

    if(this.status>=200&&this.status<300)
        callback(WebAssembly.instantiate(x.responseText.arrayBuffer(), importObject).instance.exports);
    else return "Error: "+this.status+" "+this.statusText;
}

x.open("GET","file.wasm");
x.send();

The above snippet is the complete code, just to be safe. Otherwise, here is a minimal example:

var x = new XMLHttpRequest();

x.onreadystatechange=function(){
    if(this.readyState==4 && this.status===200)
        callback(WebAssembly.instantiate(x.responseText.arrayBuffer(), importObject).instance.exports);
}

x.open("GET","file.wasm");
x.send();

What is the process to rewrite this fetch() code to XMLHttpRequest() code?

Clarification: The reason my (XMLHttpRequest) code doesn't work is because it throws a TypeError:

Uncaught TypeError: x.responseText.arrayBuffer is not a function
    at XMLHttpRequest.x.onreadystatechange (wasm.js)

x.onreadystatechange @ wasm.js

XMLHttpRequest.send (async)

(anonymous) @ wasm.js

Solution

  • request = new XMLHttpRequest();
    request.open('GET', 'simple.wasm');
    request.responseType = 'arraybuffer';
    request.send();
    
    request.onload = function() {
      var bytes = request.response;
      WebAssembly.instantiate(bytes, importObject).then(results => {
        callback(results);
      });
    };
    

    I took the example from here https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running