首先-我们在这里是无人涉足的领域,所以当它在最新的firefoxes中工作时,MDN上的文档在撰写本文期间还没有准备好。我稍后会修复MDN (可能有很多地方需要修复),所以我会提供一个glossary。
我想从回调中创建一个迭代器:
我有一个使用两个回调作为参数构造的类。让我们将实例命名为“listener”。然后,此侦听器使用某个参数重复调用第一个回调,直到完成侦听,然后调用第二个回调一次。
我想围绕它包装一个迭代器,它产生侦听器调用第一个回调时使用的每个参数,然后在调用第二个回调时立即抛出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
请注意,我是在一个and addon中完成所有这些工作的,所以我可以使用promises和相关的东西。并且不需要关于浏览器如何不知道我要做的任何事情的讲座;)
/edit:如果你问我为什么不直接把所有东西都转换成基于回调的代码,have a taste告诉我怎么把它转换成基于回调的代码而不哭。我将把我的主函数封装到前面提到的here中。
发布于 2013-06-28 09:07:15
我认为你可以用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();
参考
https://stackoverflow.com/questions/16694511
复制相似问题