Skip to content
Advertisement

Async generator class stuck on infinite loop javascript

I’m trying to get the following async generator to work:

JavaScript

But it ends up in an infinite loop, and thing is always undefined.

JavaScript

I’ve tried a similar code, but this time without the Promise/async behaviour, and it seems to work just fine.

JavaScript
JavaScript

Advertisement

Answer

The for await..of construct will attempt to iterate over an async iterator.

An async iterator is defined using the @@asyncIterator well-known symbol:

JavaScript

for await..of can also consume plain iterables that produce promises:

JavaScript

Attempting to make a regular iterator that is an async method/function does not work.

If you want to keep your @@iterator defined method your the best choice is to make it produce promises instead:

JavaScript

Although, that’s might be a bad practice if any of the promises rejects:

JavaScript

Screenshot of the browser console from running the above snippet. Results are identical to the comment left in at the end of the snippet.

However, be aware that there is a difference in semantics between these:

  • A regular iterator produces an IteratorResult – an object with value and done properties.

JavaScript
  • An async generator produces a promise for an IteratorResult

JavaScript
  • Finally, an iterator that produces promises will have an IteratorResult where value is a promise:

JavaScript

Side-note on nomenclature: MyIterator is not an iterator. An iterator is an object with a next() method which produces an IteratorResult. An object that you can iterate over has an @@iterator (or @@asyncIterable) method and it is called iterable (or async iterable respectively).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement