Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 14 题:简单实现async/await中的async函数 #14

Open
airuikun opened this issue Apr 14, 2019 · 1 comment
Open

第 14 题:简单实现async/await中的async函数 #14

airuikun opened this issue Apr 14, 2019 · 1 comment

Comments

@airuikun
Copy link
Owner

airuikun commented Apr 14, 2019

async 函数的实现原理,就是将 Generator 函数和自动执行器,包装在一个函数里

function spawn(genF) {
    return new Promise(function(resolve, reject) {
        const gen = genF();
        function step(nextF) {
            let next;
            try {
                next = nextF();
            } catch (e) {
                return reject(e);
            }
            if (next.done) {
                return resolve(next.value);
            }
            Promise.resolve(next.value).then(
                function(v) {
                    step(function() {
                        return gen.next(v);
                    });
                },
                function(e) {
                    step(function() {
                        return gen.throw(e);
                    });
                }
            );
        }
        step(function() {
            return gen.next(undefined);
        });
    });
}
@zheeeng
Copy link

zheeeng commented Apr 16, 2019

同样的效果

function spawn(genF) {
    return new Promise(function(resolve, reject) {
        const gen = genF()
        try {
            while (true) {
                const next = gen.next()
                if (!next.done) continue
                
                resolve(next.value)
                break
            }
        } catch (e) {
            return reject(e);
        }
    })
}

这是不是简单多了
谬,理解错题意了

function spawn(genF) {
    const gen = genF()

    return function next (v) {
        return new Promise((resolve, reject) => {
            try {
                const result = gen.next(v)
                if (result.done) {
                    return resolve(result.value)
                }

                return Promise.resolve(result.value).then(next).then(resolve, reject)
            } catch (e) {
                reject(e)
            }
        })
    } ()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants