I try to understand javascript async iterables by learning the javascript.info chapter.
Now I wanted to rewrite this code example that [Symbol.asyncIterator]() just sets the this.current value and then return this. I want to have the async next function definition directly in the range object.
My current attempt is the following, but does not actually do what its supposed. It should wait one second, outputs 1. Then wait another second, outputs 2. And so on (until 5).
let range = {
from: 1,
to: 5,
[Symbol.asyncIterator]() {
this.current = this.from
return this
},
next() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(this), 1000)
});
promise.then(
function(result) {
if (result.current <= result.last) {
return { done: false, value: result.current++ };
} else {
return { done: true };
}
}
)
}
};
(async () => {
for await (let step of range) {
console.log(step)
}
})()
It gives me
file:///test.mjs:29
for await (let step of range) {
^
TypeError: Iterator result undefined is not an object
Any explanation and suggestions would be much appreciated! <3