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

假如想象 提交于 2020-03-22 03:55:01

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!