[Javascript] Create an Async Generator and Loop Through Generated Promises with "For Await Of" Loops

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()

 

 

posted @ 2020-03-22 02:59  Zhentiw  阅读(160)  评论(0编辑  收藏  举报