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?