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

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12543892.html