This is the 29th day of my participation in the August Text Challenge.

JavaScript advanced

JavaScript Advanced (2)

JavaScript advanced (three) modular

JavaScript advanced (4) anti-shake

JavaScript advanced (five) throttling

JavaScript advanced (6) inheritance

Call, apply, bind

Generator will be familiar to students who write react. React middleware, React-Saga, makes full use of this data type. Cut the crap, Let’s go!

The Generator to realize

Generator is a new data type introduced by the ES6 standard. The Generator looks like a normal function that can return multiple times and, like Promise, can be used for asynchronous programming. It draws on the concept and syntax of Python’s generator. Of course you know Python’s Generator, so I’m sure this should be fairly simple for you.

// * indicates that this is a Generator function

// Pause the code with yield

// Call next to resume execution

function* test() {

    let add = 1 + 2;

    yield 2;

    yield 3;

}

let b = test();

console.log(b.next()); // > { value: 2, done: false }

console.log(b.next()); // > { value: 3, done: false }

console.log(b.next()); // > { value: undefined, done: true }
Copy the code

As you can see from the above code, this function has a next function that returns an object. When we call next, we run the code before yield, output the result after yield, pause the code, call it again, pause, and finally execute all the yield. The following is a simple implementation of the Generator function

// cb compiled test function
function generator(cb) {
    return (function () {
        var object = {
            next: 0,
            stop: function() {}};return {
            next: function () {
                var ret = cb(object);
                if (ret === undefined) return {value: undefined, done: true};
                return {
                    value: ret,
                    done: false
                };
            }
        };
    })();
}

// If you compile with Babel you can see that the test function looks like this
function test() {
    var a;
    return generator(function (_context) {
        while (1) {
            switch ((_context.prev = _context.next)) {
                // You can find that the code is broken up into chunks by yield
                // Execute a block of code each time you execute the next function
                // And indicate which piece of code needs to be executed next
                case 0:
                    a = 1 + 2;
                    _context.next = 4;
                    return 2;
                case 4:
                    _context.next = 6;
                    return 3;
                // The execution is complete
                case 6:
                case "end":
                    return _context.stop(a); }}}); }Copy the code

Ok, that’s all for today. See you tomorrow. I’m Augus, a software developer who likes to mess around. END~~~