繁体   English   中英

有没有办法将变量从 Javascript 中的不同模块传递给导出的生成器?

[英]Is there a way to pass a variable to an exported generator from a different module in Javascript?

我正在编写一个包含两个模块的代码。 我试图将第一个模块中的变量作为第二个模块的生成器函数中的参数传递。

这是我的代码到目前为止的样子。 我试图在第二个模块的生成器 (function*) 函数中 console.log one

模块 2::

var fn = function* () {

     yield console.log(one);

     yield console.log('done');
}

var gen = fn();


module.exports = {gen}

模块 1::

var app = require('./app');
var one = 1;

app.gen.next(one);
app.gen.next();

我曾尝试在fn()function* ()中将一个作为参数传递,但这没有用。

我希望从第二个模块的控制台日志中看到的输出是 ::

1
done
  const fn = function* () {
    console.log(yield);
    yield;
    console.log('done');
  }

  const gen = fn();
  gen.next();
  gen.next(1); // 1
  gen.next(); // "done"

yield评估为您传入next() 您不能“共享”变量,只能“共享”值。

我曾尝试在 fn() 和 function* () 中将一个作为参数传递,但这没有用。

如果您导出生成器本身,那将起作用:

 const fn = function* (one) {
    yield console.log(one);
    yield console.log('done');
 }

 var gen = fn(1); 
 gen.next();  // 1
 gen.next(); // "done"

生成器函数参数可以用于实例化:用 next 传递 1 个值有点奇怪

 const fn = function* (arg) { let foo = arg foo += yield foo // 1 foo += yield foo // 2 foo += yield foo // 3 } var one = 'abc=>' let gen = fn(one) console.log( gen.next('x') ) console.log( gen.next('y') ) console.log( gen.next('z') ) console.log( gen.next('bye') )
 .as-console-wrapper { max-height: 100% !important }

谢谢大家的回复。 我终于找出了我代码中的错误。 我的错误是声明var gen = fn(); 在错误的模块中; 它应该在 module1 中声明如下:

var app = require('./app');
var one = 1;
var gen = app.fn(one); // First correction made here

gen.next();
gen.next();

在我修改后的代码中,我在 module1 中声明了它并通过它传递了one作为参数,然后它将在 module2 中访问为:

var fn = function* (one) {... // Second correction made here

然后导出生成器函数而不是最后导出生成器对象,如下所示:

module.exports = {fn}

最终修订代码

所以现在这两个模块如下:

应用程序1.js

var app = require('./app');
var one = 1;
var gen = app.fn(one); // First correction made here

gen.next();
gen.next();

应用程序.js

var fn = function* () {

     yield console.log(one);

     yield console.log('done');
}


module.exports = {fn}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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