What can we do with the ES6 Generator that we cannot work with for a loop?

I went through ES6 and the generators caught me. One thing that has come out of sight is the union of Promise objects, which I could not do with loops. What other mechanics can we do that we could not do before?

I understand that this is a broad question, but I can’t think of anything other than Promises at the moment.

+5
source share
1 answer

Using yield, generators can be paused at any point in the control flow of your function, saving your current execution state (scope and stack).

Without generators, this is more complicated:

  • () , .

, , . DFS/BFS .

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

Source: https://habr.com/ru/post/1540252/


All Articles