Generator not evaluating promises

╄→гoц情女王★ 提交于 2019-12-11 07:24:34

问题


Why doesn't the generator wait for the asynchronous prm promise to complete before moving on to the next yield?

function *verify() {
    try {
        let prm = new Promise((resolve,reject) => {
            resolve("abc");
        })
        let k = yield prm
        console.log(k)
        yield 1;
        console.log("1")
        yield 2;
        console.log("2")
        yield 3;
        console.log("3")
    } catch (err) {
        console.log("error")
    }
}

var gen = verify()
while (!gen.next().done) {}

returns

undefined
1
2
3

回答1:


Because a generator - on its own - doesn't wait for anything. It just emits what you were yielding from the next() call. You could of course have your loop wait when before calling next again when it gets a promise.

What you are thinking of is async/await. You want to write

async function verify() {
    try {
        let prm = new Promise((resolve,reject) => {
            resolve("abc");
        })
        let k = await prm
        console.log(k)
        console.log("1")
        console.log("2")
        console.log("3")
    } catch (err) {
        console.log("error")
    }
}

var prm = verify();


来源:https://stackoverflow.com/questions/44083873/generator-not-evaluating-promises

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