【问题标题】:Can node-fibers be implemented using ES6 generators?节点光纤可以使用 ES6 生成器实现吗?
【发布时间】:2015-07-30 05:48:54
【问题描述】:

维基百科建议coroutines can be implemented with generators。这是否意味着node-fibers 可以使用ES6 generators 来实现?

【问题讨论】:

    标签: node.js generator coroutine ecmascript-harmony node-fibers


    【解决方案1】:

    你在寻找类似https://github.com/visionmedia/co 的东西吗?

    来自自述文件:

    var co = require('co');
    
    co(function *(){
      var a = yield get('http://google.com');
      var b = yield get('http://yahoo.com');
      var c = yield get('http://cloudup.com');
      console.log(a.status);
      console.log(b.status);
      console.log(c.status);
    })()
    
    co(function *(){
      var a = get('http://google.com');
      var b = get('http://yahoo.com');
      var c = get('http://cloudup.com');
      var res = yield [a, b, c];
      console.log(res);
    })()
    

    有一个基于此的名为 koa (http://koajs.com) 的新 Web 框架。

    【讨论】:

    • 好东西。感谢您的提醒。我想知道是否有可能在生成器之上构建与fibrous 语法兼容的东西。我相信不是。
    【解决方案2】:

    我在 Fibers 周围编写了一个名为 wait.for 的包装器:https://github.com/luciotato/waitfor

    然后我用生成器编写了相同的功能https://github.com/luciotato/waitfor-ES6

    您可以比较两者以了解生成器如何替换节点光纤,但语法不同。

    一个重要的区别是不可能拥有相同的 API, 是 ES6 的生成器主体是用特殊语法实现的:function* 而 node-fibers 允许你使用任何 js 函数。

    【讨论】:

      【解决方案3】:

      tried to port a very small subset 失败了。关键是 node-fibers 的 Fiber.yield() 会一直停止执行 Fiber 的调用堆栈,而生成器的 yield 只会停止立即函数。虽然您可能能够实现一个行为相似的系统(如Task.js),但似乎无法实现与 API 兼容的实现。

      【讨论】:

      • 您是否尝试使用yield*?它允许您嵌套生成器函数,以便您也可以在嵌套的生成器函数中产生。
      • 链接断开!请修复。
      • @nalply,已修复。谢谢!
      猜你喜欢
      • 2013-11-13
      • 2012-07-26
      • 2013-06-16
      • 2018-02-18
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      相关资源
      最近更新 更多