09. Async Generators
Async generators a mixture of async functions and generators. Normal (synchronous) generators help with implementing synchronous iterables. Asynchronous generators do the same for asynchronous iterables. Async generators allow you to create async iterator factories.
An async generator returns a generator object which follows iterator specification.
Each invocation
genObj.next()
returns a Promise for an object{value, done}
that wraps a yielded value.Generator doesn't have a natural end - you can't check the end directly and should await for promise to be resolved to get
done
Like all for-loops
, you can break whenever you want. This results in the loop calling iterator.return()
, which causes the generator to act as if there was a return statement after the current (or next) yield.
Async generator execution:
Каждый вызов
next()
возвращает Promise.Последующий вызов
next()
вернет следующий Promise безотносительно результата предыдущего Promise (нет необходимости ждать, пока предыдущий Promise будет установлен).next()
вызовы являются неблокирующими.Узнать, закончился ли генератор, можно только дождавшись когда Promise будет установлен и проверив значение
done
.У асинхронного генератора нет понятия "длинны" или "количества доступных элементов".
Поэтому асинхронные генераторы не поддерживают
spread
оператор.yield x
fulfills the “current” Promise with{value: x, done: false}
.throw err
rejects the “current” Promise witherr
.In normal generators,
next()
can throw exceptions. In async generators,next()
can reject the Promise it returns.
await
in async generators
await
in async generatorsYou can use await
and for-await-of
inside async generators. For example:
One interesting aspect of combining await
and yield
is that await
can’t stop yield
from returning a Promise, but it can stop that Promise from being settled.
Fetch number of elements
Retrieving Promises to be processed via Promise.all()
. If you know how many elements there are in an async iterable, you don’t need to check done
.
Async data operations
Async generators as sinks for data, where you don’t always need to know when they are done:
Async generators in depth
a rough approximation of how async generators work:
Last updated
Was this helpful?