What are Asynchronous iterators and generators?

Asynchronous iterators and generators

Iterators are objects that allow the traversal of iterables. They often have return values at their end.

Generators are functions that allow uncontinuous execution. They act as a special kind of iterator and only run when the next value is needed.

Regular iterators and generators do not allow the use of asynchronous operations, like file reading, inside their functions. To allow such operations, some languages have asynchronous iterators and generators.

Asynchronous Iterators

Asynchronous Iterators are iterators that allow asynchronous operations inside. To demonstrate how an asynchronous iterator is written, the following example converts a regular iterator to an asynchronous one:

As can be seen in the example, only minor changes are needed to convert a regular synchronous iterator into an asynchronous iterator. Both iterators are used here to traverse a list.

There is no async operation being used in the asynchronous iterator in the example above.

Asynchronous Generators

Asynchronous generators are also quite similar to synchronous generators, as the following example demonstrates:

Again, this example only iterates over a list and prints its content. No asynchronous operation is being used in the asynchronous generator; however, it is completely possible to use​.

Copyright ©2024 Educative, Inc. All rights reserved