8

一段时间以来,我一直对 Node JS 感到非常兴奋。我最终决定认真编写一个测试项目来了解最新的 Harmony 构建的 Node.js 中的生成器。

这是我非常简单的测试项目:

https://github.com/kirkouimet/project-node

要运行我的测试项目,您可以轻松地从 Github 中提取文件,然后使用以下命令运行它:

node --harmony App.js

这是我的问题 - 我似乎无法让 Node 的异步 fs.readdir 方法与生成器内联运行。其他项目,例如Galaxysuspend似乎能够做到这一点。

这是我需要修复的代码块。我希望能够实例化 FileSystem 类型的对象并在其上调用 .list() 方法:

https://github.com/kirkouimet/project-node/blob/4c77294f42da9e078775bb84c763d4c60f21e1cc/FileSystem.js#L7-L11

FileSystem = Class.extend({

    construct: function() {
        this.currentDirectory = null;
    },

    list: function*(path) {
        var list = yield NodeFileSystem.readdir(path);

        return list;
    }

});

我需要提前做些什么来将 Node 的 fs.readdir 转换为生成器吗?

一个重要的注意事项是,我正在解析所有创建的类函数。这让我能够以不同于普通函数的方式处理生成器函数:

https://github.com/kirkouimet/project-node/blob/4c77294f42da9e078775bb84c763d4c60f21e1cc/Class.js#L31-L51

我真的被这个项目难住了。希望有任何帮助!

这是我想要完成的事情:

  1. 大量使用类,修改版本的 John Resig 的 JavaScript 类支持继承
  2. 使用生成器获得对 Node 的股票异步调用的内联支持

编辑

我试图实现您的示例功能,但遇到了一些麻烦。

list: function*(path) {
    var list = null;

    var whatDoesCoReturn = co(function*() {
        list = yield readdir(path);
        console.log(list); // This shows an array of files (good!)
        return list; // Just my guess that co should get this back, it doesn't
    })();
    console.log(whatDoesCoReturn); // This returns undefined (sad times)

    // I need to use `list` right here

    return list; // This returns as null
}
4

2 回答 2

17

首先也是最重要的,重要的是在您的头脑中建立一个好的模型来准确地了解生成器是什么。生成器函数是一个返回生成器对象的函数,该生成器对象将yield在您调用它时逐步执行生成器函数中的语句.next()

鉴于该描述,您应该注意到未提及异步行为。对生成器本身的任何操作都是同步的。您可以立即运行到第一个yield,然后执行 asetTimeout然后调用.next()转到下一个yield,但它是setTimeout导致异步行为的原因,而不是生成器本身。

因此,让我们根据fs.readdir. fs.readdir是一个异步函数,单独在生成器中使用它不会有任何效果。让我们看看你的例子:

function * read(path){
    return yield fs.readdir(path);
}

var gen = read(path);
// gen is now a generator object.

var first = gen.next();
// This is equivalent to first = fs.readdir(path);
// Which means first === undefined since fs.readdir returns nothing.

var final = gen.next();
// This is equivalent to final = undefined;
// Because you are returning the result of 'yield', and that is the value passed
// into .next(), and you are not passing anything to it.

希望它可以更清楚地说明您仍在readdir同步调用的内容,并且您没有传递任何回调,因此它可能会抛出错误或其他东西。

那么如何从生成器中获得良好的行为呢?

通常,这是通过让生成器产生一个特殊对象来完成的,该对象表示readdir实际计算值之前的结果。

对于(不切实际的)示例,yield函数是产生表示值的东西的简单方法。

function * read(path){
    return yield function(callback){
        fs.readdir(path, callback);
    };
}

var gen = read(path);
// gen is now a generator object.

var first = gen.next();
// This is equivalent to first = function(callback){ ... };

// Trigger the callback to calculate the value here.
first(function(err, dir){
  var dirData = gen.next(dir);
  // This will just return 'dir' since we are directly returning the yielded value.

  // Do whatever.
});

实际上,您会希望这种类型的逻辑继续调用生成器,直到所有yield调用都完成,而不是对每个调用进行硬编码。不过要注意的主要一点是,现在生成器本身看起来是同步的,并且read函数之外的所有内容都是超级通用的。

您需要某种生成器包装函数来处理此产值过程,而您的示例suspend正是这样做的。另一个例子是co

“返回代表值的东西”方法的标准方法是返回 apromise或 athunk因为像我一样返回一个函数有点难看。

使用thunkandco库,您可以在没有示例函数的情况下执行上述操作:

var thunkify = require('thunkify');
var co = require('co');
var fs = require('fs');
var readdir = thunkify(fs.readdir);

co(function * (){
    // `readdir` will call the node function, and return a thunk representing the
    // directory, which is then `yield`ed to `co`, which will wait for the data
    // to be ready, and then it will start the generator again, passing the value
    // as the result of the `yield`.
    var dirData = yield readdir(path, callback);

    // Do whatever.
})(function(err, result){
    // This callback is called once the synchronous-looking generator has returned.
    // or thrown an exception.
});

更新

您的更新仍然有些混乱。如果您希望您的list函数成为生成器,那么您将需要在调用它的任何地方co 之外使用。list里面的一切都co应该是基于生成器的,而外面的一切都co应该是基于回调的。co不会list自动异步。co用于将基于生成器的异步流控制转换为基于回调的流控制。

例如

list: function(path, callback){
    co(function * (){
      var list = yield readdir(path);

      // Use `list` right here.

      return list;
    })(function(err, result){
      // err here would be set if your 'readdir' call had an error
      // result is the return value from 'co', so it would be 'list'.

      callback(err, result);
    })
}
于 2014-03-19T02:55:39.960 回答
9

@loganfsmyth 已经为您的问题提供了很好的答案。我回答的目的是帮助您了解 JavaScript 生成器的实际工作原理,因为这是正确使用它们的非常重要的一步。

生成器实现了一个状态机,这个概念本身并不是什么新鲜事。新的是,生成器允许使用熟悉的 JavaScript 语言结构(例如,、、、foriftry/catch实现状态机,而不会放弃线性代码流。

生成器最初的目标是生成一个数据序列,这与异步无关。例子:

// with generator

function* sequence()
{
    var i = 0;
    while (i < 10)
        yield ++i * 2;
}

for (var j of sequence())
    console.log(j);

// without generator

function bulkySequence()
{
    var i = 0;
    var nextStep = function() {
        if ( i >= 10 )
            return { value: undefined, done: true };
        return { value: ++i * 2, done: false };
    }
    return { next: nextStep };
}

for (var j of bulkySequence())
    console.log(j);

第二部分 ( bulkySequence) 展示了如何在不使用生成器的情况下以传统方式实现相同的状态机。在这种情况下,我们不再能够使用while循环来生成值,并且继续通过nextStep回调发生。此代码庞大且不可读。

让我们介绍一下异步。在这种情况下,状态机下一步的继续将不是由for of循环驱动,而是由一些外部事件驱动。我将使用计时器间隔作为事件的来源,但它也可以是 Node.js 操作完成回调,或 Promise 解析回调。

这个想法是在不使用任何外部库(如QBluebird等)的情况下展示它是如何工作的Co。没有什么能阻止发电机自动驾驶到下一步,这就是以下代码的作用。一旦异步逻辑的所有步骤都完成(10 个计时器滴答声),doneCallback将被调用。请注意,我不返回任何有意义的数据yieldhere。我只是用它来暂停和恢复执行:

function workAsync(doneCallback)
{
    var worker = (function* () {
        // the timer callback drivers to the next step
        var interval = setInterval(function() { 
            worker.next(); }, 500);

        try {
            var tick = 0;
            while (tick < 10 ) {
                // resume upon next tick
                yield null;
                console.log("tick: " + tick++);
            }
            doneCallback(null, null);
        }
        catch (ex) {
            doneCallback(ex, null);
        }
        finally {
            clearInterval(interval);
        }
    })();

    // initial step
    worker.next();
}

workAsync(function(err, result) { 
    console.log("Done, any errror: " + err); });

最后,让我们创建一个事件序列:

function workAsync(doneCallback)
{
    var worker = (function* () {
        // the timer callback drivers to the next step
        setTimeout(function() { 
            worker.next(); }, 1000);

        yield null;
        console.log("timer1 fired.");

        setTimeout(function() { 
            worker.next(); }, 2000);

        yield null;
        console.log("timer2 fired.");

        setTimeout(function() { 
            worker.next(); }, 3000);

        yield null;
        console.log("timer3 fired.");

        doneCallback(null, null);
    })();

    // initial step
    worker.next();
}

workAsync(function(err, result) { 
    console.log("Done, any errror: " + err); });

一旦你理解了这个概念,你就可以继续使用 Promise 作为生成器的包装器,这将它提升到一个强大的水平。

于 2014-03-20T04:09:23.393 回答