【问题标题】:Are generators really intrusive生成器真的具有侵入性吗
【发布时间】:2013-06-08 21:03:01
【问题描述】:

据我了解当前的 Javascript 生成器规范,您必须明确标记包含 yields 的函数。

我想知道这背后的合理性是什么。

如果这是真的,那将迫使人们写作:

let thirdfunc = function*() {
  let value = 5;
  let other = yield 6;
  return value;
};

let secondfunc = function*() {
  yield thirdfunc();
};

let firstfunc = function*() {
  yield secondfunc();
};

let gen = function*() {
  // some code
  // more code
  yield firstfunc();
  // and code
};

let it = gen();
while( !it.done() ) {
  it.next();
};

这意味着,生成器会像癌症一样在代码库中传播。 最后,对于开发人员来说,只产生和处理迭代器真的很有趣。

我会发现它更实用,只需定义我想要处理迭代的位置。

let thirdfunc = function() {
  let value = 5;
  let other = yield 6; // Change 1: incorporate yield
  return value;
};

let secondfunc = function() {
  thirdfunc();
};

let firstfunc = function() {
  secondfunc();
};

let gen = function*() { // Change 2: at this level I want to deal with descendant yields
  // some code
  // more code
  firstfunc();
  // and code
};

// Change 3: Handle iterator
let it = gen();
while( !it.done() ) {
  it.next();
}

如果浏览器必须将yield 调用和生成器处理程序(firstfuncsecondfuncthirdfunc)之间的所有内容转换为 promise / future em> 表单,它应该自动运行,而不是 Javascript 开发人员的业务。

或者说不这样做真的有很好的理由吗?

【问题讨论】:

  • “我想知道这背后的理由是什么。” 老实说,我建议直接联系从事规范或邮件列表/论坛/等工作的人。

标签: javascript generator ecmascript-harmony ecmascript-6


【解决方案1】:

我在http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ 描述了设计这方面的基本原理——简而言之,完整的协程(就是你所描述的)干扰了 JavaScript 的运行到完成模型的精神,使得更难预测何时您的代码可以在类似于 Java、C# 和 C++ 等多线程语言的意义上被“抢占”。博客文章更详细地介绍了一些其他原因。

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 2011-02-11
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2022-06-16
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多