了解产量/生成器的代码流

Exp*_*lls 5 javascript yield generator node.js co

我已经阅读了几个使用JavaScript生成器的代码示例,例如这个.我能想到的最简单的生成器使用块是这样的:

function read(path) {
    return function (done) {
        fs.readFile(path, "file", done);
    }
}

co(function *() {
    console.log( yield read("file") );
})();
Run Code Online (Sandbox Code Playgroud)

这确实打印出了内容file,但我的挂断是在哪里done调用.看起来,yield是一个语法糖,用于包装它在回调中返回的内容并适当地分配结果值(至少在co将错误参数抛给回调的情况下).我对语法的理解是否正确?

使用done时看起来像什么yield

nos*_*tio 2

我在这里发布了生成器如何工作的详细解释。

以简化的形式,您的代码可能看起来像这样,没有co(未经测试):

function workAsync(fileName)
{
    // async logic
    var worker = (function* () {

        function read(path) {
            return function (done) {
                fs.readFile(path, "file", done);
            }
        }

        console.log(yield read(fileName));
    })();

    // driver
    function nextStep(err, result) {
        try {
            var item = err? 
                worker.throw(err):
                worker.next(result);
            if (item.done)
                return;
            item.value(nextStep);
        }
        catch(ex) {
            console.log(ex.message);
            return;
        }
    }

    // first step
    nextStep();
}

workAsync("file");
Run Code Online (Sandbox Code Playgroud)

的驱动程序部分workAsync通过调用 异步迭代生成器对象nextStep()