Generators can yield promises which can work with the "for await of" loop syntax. This lesson shows how all the pieces fit together and explains why the async function* syntax can be necessary for certain situations.

 

async function* users() {
    let names = ["johnlindquist", "eggheadio"]
    for (let name of names) {
        let response = await fetch(`https://api.github.com/users/${name}`)
        yield response.json()
    }
}

async function start() {
    for await (let user of users()) {
        console.log(user.name)
    }
}

start()

 

相关文章: