我们可以用 ES6 Generator 做什么而不能用 for 循环? [英] What can we do with ES6 Generator that we cannot with for loop?
问题描述
我了解了 ES6 的特性,而 Generators 引起了我的注意.我想到的一件事是链接 Promise 对象,而我无法用循环来做.我们将能够做哪些其他机制,而我们以前无法做到?
I went trough ES6 features and Generators caught my eye. One thing that sprang to mind is chaining Promise objects, that I could not do with loops. What other mechanics we will be able to do, that we could not before?
我确实理解这是一个宽泛的问题,但目前除了 Promises 之外我想不出任何其他的东西.
I do understand this is broad question, still I can't think of anything but Promises at the moment.
推荐答案
通过使用 yield
,可以在函数的控制流中的任何点暂停生成器,从而保存当前的执行状态(范围和堆栈).
By using yield
, generators can be suspended at any point in the control flow of your function, saving your current state of execution (scope & stack).
如果没有生成器,这会更复杂:
Without generators, this is more complicated:
- 您需要明确跟踪状态
- 分支和(尤其是)循环控制结构需要以函数方式表示,即递归编写.
生成器通常用于遍历数据结构,创建一个简单的类似流的迭代器,按顺序生成所有元素.对于简单的例子,可以考虑树遍历或图中的 DFS/BFS.
Generators are generically useful for traversing data structures, creating a simple stream-like iterator that yields all elements in order. Think of tree traversal, or DFS/BFS in graphs for simple examples.
function* traverseTree(node) {
if (node == null) return;
yield* traverseTree(node.left);
yield node.value;
yield* traverseTree(node.right);
}
// vs (not sure):
function traverseTree(node) {
var rl, l, r;
return {
next: function() {
if (node == null && !r) return {done:true};
if (!l) l = traverseTree(node.left);
if (!(rl=l.next()).done)
return rl;
if (node != null) {
var n = {value:node.value};
node = null;
r = traverseTree(node.right);
return n;
}
return r.next();
}
}
}
这篇关于我们可以用 ES6 Generator 做什么而不能用 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!