Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

javascript - What can we do with ES6 Generator that we cannot with for loop?

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?

I do understand this is broad question, still I can't think of anything but Promises at the moment.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • you need to explicitly keep track of the state
  • branching and (especially) looping control structures need to be represented in a functional way, i.e. written recursively.

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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...