...

/

Async Generators

Async Generators

Learn how to use an async generator to implement an async iterator.

Similar to async iterators, we can also have async generators. To define an async generator function, simply prepend the async keyword to the function definition.

async function * generatorFunction() {
// ...generator body
}

As we can well imagine, async generators allow the use of the await instruction within their body and the return value of their next() method is a promise that resolves to an object having the canonical done and value properties. This way, async generator objects are also valid async iterators. They are also valid async iterables, so they can be used in for await...of loops.

To demonstrate how async generators can simplify the implementation of async iterators, let’s convert the CheckUrls class to use an async generator.

Press + to interact
index.js
checkUrls.js
package.json
{
"name": "11-async-generator-check-url",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"superagent": "^5.2.2"
},
"engines": {
"node": ">=14"
},
"engineStrict": true
}
...