有什么办法导出生成器函数吗?

JavaScript KoaJS

小宇宙

2020-03-30

一个例子

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

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

第3840篇《有什么办法导出生成器函数吗?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
小胖 2020.03.30

这可能是问题所在:

NodeJS控制台SyntaxError:生成器意外的令牌*

此外,我不会导出任何不是对象的东西,尤其是在ES6中,它具有可使用的类。

JinJin 2020.03.30

您可以导出所需的任何内容,但是请不要在公共模块中导出生成器函数。生成器是控制流黑客。相反,用co@4

exports.fn = co.wrap(function* () {
  return yield something() 
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android