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

Constance in JavaScript

Looking to create constants in Javascript and seeking advice on the best way to do so. While I am aware that true constants don't technically exist, I'm finding it difficult to change values after exporting them. Are constants necessary? Is the ...

Seek within a popup window and refresh the content of a DIV element on the main page

Yet again, it's the late hours of the night and I find myself facing a seemingly simple issue that's causing quite the headache! Here's the scenario: I have a basic HTML form inside a Bootstrap modal. Upon submitting this form, an AJAX POST ...

What could be the reason for the full name not being updated in the model when the last name is changed

Can you explain why the full name in the model does not update when I change the last name? You can view the code on Plunker: http://plnkr.co/edit/cqmwJc5dpoDWvai4xeNX?p=preview var loginCntrl=function($scope){ $scope.testClick =function(){ $scope. ...

Show a webpage depending on specific JavaScript criteria

I have a condition in my JavaScript code that determines whether or not a user should be granted access to a specific page. However, I don't want users to be able to directly access this page even if they know the URL. This page contains both HTML and ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

Using .done(), .then(), and .when() in jQuery for sequencing ajax requests in a specific order

After diving into the world of Promises in jquery and trying to avoid "callback hell" when dealing with multiple ajax requests, I still find myself without a clear answer on which method to use - whether it's .done(), .then(), or .when() - for chainin ...

The DateFormat.js script encountered an error: Unexpected token export

While working with some Kubernetes PODS, I suddenly encountered an error in one of the pods. The issue seems to be originating from line 6 of my code. I haven't made any changes recently; I was just deploying on GitLab when I noticed that this particu ...

Codeigniter not functioning properly with Ajax

I am trying to implement this javascript function $('a[name=deleteButton]').on('click', function () { arr=[]; var arr = $("input[name='post[]']:checked").map(function() { return this.value; }). ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

Having trouble navigating back to the homepage

Recently, I started following a tutorial on YouTube to create a basic frontend in React with Bootstrap. However, I encountered a roadblock while trying to implement a specific functionality. The issue stemmed from the fact that react-router-dom v6 no lon ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

The Angular 2 http request for a POST method is not initiating

Utilizing Angular 2, I have successfully implemented a get request function. However, when attempting to make a post request, I am unable to detect any sign of the request in the Firebug Net panel. The code for these methods is as follows. Furthermore, th ...

How can I incorporate a child component into a separate component within Angular version 14?

Currently working with Angular 14 and facing a challenge with including a child component from another module into a standalone component. The structure of the standalone component is as follows: <div> <child-component></child-component& ...

Revert animation back to its initial position with the help of JavaScript

After implementing the script below, I successfully managed to shift my image to the right upon clicking: <script> var myTimer = null; function move(){ document.getElementById("fish").style.left = parseInt(document.getElementById("fish ...

Host app is failing to render shared components in SSR

Encountering an issue while implementing SSR with module federation? Check out my code example Steps to Begin: Run yarn install:all command Execute yarn shell:server:build task Start the server using yarn shell:server:start Initiate remote services with y ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

Transferring Image through Email using AJAX Technology

By using the following code snippet, I have successfully managed to send an email with an attached image from a different server: <$php $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="225b4d575062474f434b4e0c414d4f"&g ...

Using AJAX to refresh a div upon submitting a form, instead of reloading the entire page

My SQL database generates a table that remains hidden until the search button is clicked to display the results. I want to use ajax to update the table without refreshing the entire page. Currently, when the page refreshes, the table reverts back to being ...