【问题标题】:ECMA harmony – callback to generatorECMA 和谐 – 回调到生成器
【发布时间】:2013-05-17 16:00:14
【问题描述】:

首先——我们在这里处于未开发的领域,所以虽然它可以在最新的 Firefox 中运行,但在撰写本文时,MDN 上的文档还没有准备好。稍后我会修复 MDN(可能还有很多地方需要修复),所以我会提供glossary

我想从回调中创建一个迭代器:

我有一个使用两个回调作为参数构造的类。我们称这个实例为“监听器”。然后,此侦听器使用某个参数重复调用第一个回调,直到完成侦听,然后再调用第二个回调一次。

我想围绕它包装一个迭代器,它会产生监听器调用第一个回调的每个参数,然后在调用第二个回调时立即抛出 StopIteration。

像这样:

var magicIter = new MagicIter();

var listener = new Listener(magicIter.ready, magicIter.finished);

//on another thread, listener calls ready(1); ready(2); finished();

exhaustIterator(magicIter); //loops over magicIter and does stuff with it.

//listener has called finished, so magicIter has thrown StopIteration
//so the loop in exhaustIterator has stopped

请注意,我在 Addon SDK 插件中执行所有这些操作,因此我可以使用 promises 和相关内容。并且不需要关于浏览器如何不知道我正在尝试做什么的讲座;)

/edit:如果你问我为什么不直接将所有内容都转换为基于回调的代码have a taste,并告诉我如何将其转换为基于回调的代码而不流泪。我将把我的主要功能包装成提到的东西here

【问题讨论】:

  • 我还在学习 ES6,但这听起来像是两次迭代(一个是 for..of,另一个是侦听器重复调用回调)。你想用它实现什么?
  • 令我困惑的是,您似乎想以一种不可能的方式混合同步和异步操作。
  • 我有一个基于回调的东西(监听器)和一个接受迭代器的函数(这里用 for 循环表示)。我将更改问题以澄清这一点。将所有内容都更改为基于回调的代码将是一个巨大的痛苦,因为exhaustIterator 代表子函数也接受迭代器等等。
  • bfavaretto:为什么?如果没有数据可用,magicIter.next() 应该阻塞,直到侦听器再次调用ready()。这一定是可能的,队列也可以做到这一点。

标签: javascript generator yield ecmascript-6


【解决方案1】:

我认为你可以用stream.js 做这样的事情:

var s = new Stream( 10, 
          function () 
            {
            return new Stream();
            } 
        );
            // the head of the s stream is 10; the tail is the empty stream
            s.print(); // prints 10
            var t = new Stream( 10, 
            function () 
                {
                return new Stream( 20, 
                  function () 
                    {
                    return new Stream( 30, 
                      function () 
                        {
                        return new Stream();
                        } 
                                     );
                     }   
                                 );
                } 
                              );

           /*
           the head of the t stream is 10
           its tail has a head which is 20 
           and a tail which has a head which is 30 
           and a tail which is the empty stream
           */

           t.print(); // prints 10, 20, 30

我想从回调中创建一个迭代器:

var callback_iterator =  new Stream( 1, function () {  
  return new Stream(1);  
  } );  

callback_iterator.add(callback_iterator.tail() ).print();

参考文献

【讨论】:

  • 感谢您向我展示了这一点,因为它很好;但我不明白如何将它用于我想要的。
猜你喜欢
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 2016-08-25
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
相关资源
最近更新 更多