← 中文资源

简体中文版本

生成器通过 next() 接收外部值

生成器的 next(value) 把入参送进暂停的 yield 表达式,return 的返回值则以 done:true 的结果对象浮出——迭代器由此变成双向通道。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ready
echo:hello
echo:world
{ value: 'finished', done: true }
true

实现说明

本示例的循环部分是 while (received !== 'done')。 各个操作都建立在顶层绑定之上:it。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 状态都挂在模块顶层:it。

核心语句

received = yield 'echo:' + received;
let received = yield 'ready';
return 'finished';

代码示例

function* echoPipeline() {
  // yield both produces a value and receives the argument of the next .next()
  let received = yield 'ready';
  while (received !== 'done') {
    received = yield 'echo:' + received;
  }
  return 'finished';
}

const it = echoPipeline();
// The first .next() carries no input: it runs up to the first yield
console.log(it.next().value);
console.log(it.next('hello').value);
console.log(it.next('world').value);
// Passing 'done' exits the loop; the return value lands in .value with done true
console.log(it.next('done'));
console.log(it.next().done);