What is the process for transforming fetch() into XML HTTP Requests?

In my code, I originally used fetch(), but for my specific situation, using XMLHttpRequest() would be more suitable. However, I am struggling to convert the code to utilize XMLHttpRequest().

This is the original fetch() code:

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

I attempted to rewrite it as follows:

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 contains all the necessary code. Alternatively, here is a simple 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();

How can I successfully convert the fetch() code to use XMLHttpRequest() instead?

Note: The reason why my XMLHttpRequest code is not functioning is due to 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

Answer №1

ajaxRequest = new XMLHttpRequest();
ajaxRequest.open('GET', 'example.wasm');
ajaxRequest.responseType = 'arraybuffer';
ajaxRequest.send();

ajaxRequest.onload = function() {
  var binaryData = ajaxRequest.response;
  WebAssembly.instantiate(binaryData, importObject).then(output => {
    processData(output);
  });
};

I found this helpful guide here https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Calculating the sum of all elements in an array

Hi, I am currently attempting to retrieve the total value from an array (such as Arr[1] + Arr[2], and so forth). Unfortunately, I am struggling to find a solution. Below is my existing function: this.hourlyTotals = function() { var custsperhour = Math ...

What is the process for using a click event to redirect to a different page on a website?

Currently, I am working with vue-bootstrap and I have a set of cards, each containing a button. I want each of these buttons to redirect me to a different form, but I am struggling with implementing this functionality. Below is the snippet of my code: < ...

Deactivate DropDownList within Update Panel with JQuery

Below is the Update Panel that I am working on: <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="d ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Optimally displaying extensive lists on a webpage using HTML

Are there any advanced javascript libraries that can efficiently handle loading a large list by only loading the visible part and simulating the scrollbar? <div id='container'> <!-- Empty space to mimic scrollbar, but preloading conte ...

Merge two arrays of the same size to create a single array of strings

Looking to merge the values of two equal-sized arrays and create a third array like the one shown below. I'm in need of guidance as I have not been able to locate a built-in JavaScript method for this specific task. The goal is to construct an array o ...

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functio ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Using jQuery to send a POST request with a data object

Trying to figure out something. Attempting to post an object using jQuery Ajax POST, like so: var dataPostYear = { viewType:GetViewType(), viewDate:'2009/09/08', languageId:GetLanguageId() }; $.ajax({ type: "POST", url: url ...

Using the after ship.com API with CORS in JavaScript using Ajax

Hi everyone, this is my first time posting here. I'm having trouble sending data via the POST method. When I checked the console, I saw the following error message: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

gdal.vectorTranslate causing output files to be void

Attempting to use gdal-async in nodejs for converting vector files from geojson to dxf. const dsGeoJSON2 = gdal.open('./upload2/objects.geojson'); const out2 = gdal.vectorTranslate('./upload2/objects.dxf', dsGeoJSON2, ['-f', ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

Everlasting Dropdown in AngularJS Always Open Mode

I am currently working on my first AngularJS App and I am facing some issues with creating a Dropdown menu. Here is the HTML code I have: <div class="btn-group" dropdown> <button type="button" class="btn btn-danger">Action</button> & ...

Is it possible to leverage the dimensions (width and height) of an element in JavaScript to obtain a zoom scale?

Currently experiencing an issue with the zoom level in d3.js I obtained the dimensions for the <g className ="_zoomElement"> element using this function const g = select("._zoomElement") console.log(g.node().getBBox()) My ...

The key up event in JQuery does not seem to be triggered when selecting the second option in the Select2 plugin's multi

Encountered an issue with the select2 plugin while trying to change the option list based on user input for the second multiple option. The first time I enter text in the multi-select field, the keyup event is triggered and an ajax function is called to b ...

JavaScript, Page Method, and GridView are essential components to creating dynamic and interactive

After learning how to use the page method in JavaScript and ASP.Net (VB.Net), I encountered an issue when trying to insert multiple items into a database using a gridview. Despite my efforts, there were no error messages appearing. Here is what I have so f ...

Switch between various components using multiple buttons in Next.js

I am in the process of creating a component that will display different components depending on which button the user selects. Here are the available “pages”: ` const navigation = [ { name: "EOQ", return: "<EOQgraph />" }, { nam ...