一个例子
generator.js:

exports.read = function *(){
  var a = yield read('co.github.js');
  var b = yield read('co.recevier.js');
  var c = yield read('co.yield.js');
  console.log([a,b,c]);
}

function read(file) {
  return function(fn){
    fs.readFile(file, 'utf8', fn);
  }
}
co.js:
var co = require('co');
var fs = require('fs');
var gen = require('./generator')
/*function read(file) {
  return function(fn){
    fs.readFile(file, 'utf8', fn);
  }
}*/

co(gen.read)()

似乎exports不支持生成器功能。
require, module, __filename, __dirname) { module.exports.read = function *(){
                                                                          ^
SyntaxError: Unexpected token *
at exports.runInThisContext (vm.js:69:16)
    at Module._compile (module.js:432:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Function.Module.runMain (module.js:490:10)
    at startup (node.js:123:16)
    at node.js:1027:3

为什么我要这样做?我只想将我的数据与 Controller 分开。有什么办法解决吗?

最佳答案

您可以使用变量来存储它,然后将其导出:

var myGenerator = function *() {
    // ...
}

module.exports = myGenerator;

然后,在另一个文件中,可以对其进行require:
var myGen = require('./myfirstfile.js');
// myGen is now myGenerator from above

关于javascript - 有什么办法导出生成器函数吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24388514/

10-11 22:26
查看更多