- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Async Iteration
JavaScript Generators & Iterators
JavaScript Async Iteration
for await ofloops over values that arrive one at a time, each behind a promise.
A normal generator yields values instantly.
An async generator can await before yielding each one.
Example
Example
javascript
async function* countSlowly(max) {
for (let i = 1; i <= max; i++) {
await Promise.resolve();
yield i;
}
}
async function run() {
const values = [];
for await (const n of countSlowly(3)) {
values.push(n);
}
return values.join(",");
}
run().then(function (result) {
console.log(result);
});