简体   繁体   中英

Using Generators in Node JS Inside of a Class

Alright, I need some help with generators in Node.

I really want to write code that looks like this:

require('./Class.js');
fs = require('fs');

var Directory = Class.extend({

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

    list: function*() {
        var files = [];

        yield fs.readdir(this.path, function(error, directoryFiles) {
            files = directoryFiles;
        });

        return files;
    },

});

var directory = new Directory('C:\\');
var list = directory.list();
console.log(list); // An array of files

Notes:

Is something like this possible?

You could use promises to do this so that you have proper async handling as well as built-in support for any errors.

list: function() {
  var deferred = q.defer();
  fs.readdir(this.path, deferred.makeNodeResolver());
  return deferred.promise;
}


directory.list()
  .then(function(files) { console.log(files); })
  .fail(function(err) { res.send(500,err); });

You can use a helper lib like Wait.for-ES6 (I'm the author)

Using wait.for your "list" function will be a standard async function:

 ...
list: function(callback) {
        fs.readdir(this.path, callback);
    },
 ...

but you can call it sequentially IF you're inside a generator :

function* sequentialTask(){
   var directory = new Directory('C:\\');
   var list = yield wait.forMethod(directory,'list');
   console.log(list); // An array of files
}

wait.launchFiber(sequentialTask);

Pros : You can call sequentially any standard async node.js function

Cons : You can only do it inside a generator function*

Another example: You can even do it without the 'list' function since fs.readdir IS a standard async node.js function

var wait=require('wait.for-es6'), fs=require('fs');

function* sequentialTask(){
   var list = yield wait.for(fs.readdir,'C:\\');
   console.log(list); // An array of files
}

wait.launchFiber(sequentialTask);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM