Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues:

let xhr = new XMLHttpRequest()

function *statechange() {
    yield xhr.readyState;
}

let gen = statechange();

xhr.open("GET", myUrl, true);
xhr.onreadystatechange = function() {console.log(gen.next())};
xhr.send();

Essentially, I aim to yield the ready-state of each request state change. Each iteration of the generator should log the readyState string. However, when running this code, I receive the following output:

{value: 2, done: false}
{value: undefined, done: true}
{value: undefined, done: true}

This seems correct at first glance, yet with a conventional XHR approach:

//... new XMLHttpRequest()...
xhr.onreadystatechange = function() {console.log(xhr.readyState)}

I get:

2
3
4

So, where is the flaw in my usage of generators?


UPDATE:

Oddly enough, if I log the readyState in the generator:

// HERE
xhr.onreadystatechange = function() {console.log(xhr.readyState, gen.next())};

The output is as follows:

2, {value: 2, done: false}
3, {value: undefined, done: true}
4, {value: undefined, done: true}

Therefore, the correct readyState is available when calling the next() method. It appears that the yield statement I utilized only registers once, allocating just one slot for the generator. Given that onreadystatechange is triggered multiple times, I anticipated additional slots would be assigned. How can I rectify this issue?

Answer №1

When a generator function is "called," it starts running until it reaches the first yield statement, and then it pauses until its next method is invoked. It will then resume execution until it encounters another yield statement or exits the function.

If you're looking for a loop that continuously checks the readyState of the xhr object, you can use the following generator function:

function *statechange() {
  while(true) { // continue looping indefinitely
    yield xhr.readyState;
  }
}

This behavior is similar to generators in Python.

I agree with @Paul S.'s suggestion that using generators may not necessarily simplify handling xhr objects, and you might want to explore promises as an alternative solution.

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

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

NextJS displays outcomes as per query parameters obtained from an external API

I have set up my NextJS app to connect to a rest API. The API returns results based on different filters in the query string, such as: /jobs /jobs?filter=completed /jobs?filter=upcoming /jobs?filter=cancelled On my NextJS page, I have a few buttons that I ...

Issues with transferring object data from JavaScript to a Web API

I am facing issues while attempting to transfer a file from my local machine to SharePoint using JavaScript to ASP.NET MVC Web API call. I continuously encounter errors such as Type error, resource not found, etc. Is there anyone who can provide assistance ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

How come the Jquery :odd selector picks out the even elements?

<html> <head> <script type="text/javascript" src="jquery-1.7.1.js" ></script> <script type="text/javascript"> $(function() { $("p:odd").html('modified'); }); </script> </head> & ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Sending Data From AJAX Request to Index Function

In my current project, there is a requirement to retrieve an id from an Ajax call and pass it to the Index method of the `HomeController`. The following code demonstrates how I can send the id to the controller using Ajax: Update 1: ProductRating Class: ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

I am struggling to trigger my $.ajax request when clicking a button

I'm facing an issue with my variables in the Ajax request. When I place the request outside of the .on() event, everything works fine. However, when I move the same request into the .on(), it stops working. Any assistance on this matter would be highl ...

What is the reason behind having several node modules directories within every project?

I'm just starting out with JS development and I have a question about the size of node modules. It seems that when many projects accumulate, we end up having to delete the node_modules folder because it takes up so much space. So, why isn't there ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

Exploring Angular's ng-transclude directive within a repeat loop

Recently, I began delving into AngularJS and attempted to create a custom table directive with multiple slots for transclusion. However, I encountered an issue where the scope was not being passed to the transclude. Although there are various solutions ava ...

Tips for styling an image and vCard within a Foundation accordion menu

I am working on a project that involves creating a list using an accordion feature to display names of individuals. When a user clicks on a person, I want the dropdown content to show their image and vcard details. How can I structure the content so that ...

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...