The Iterator Iterator

Iterative pattern: A design pattern used to unify the iterative process.

Javascript states that if an object has a next method and the method returns an object, the format of the object is as follows

{value: value, done: whether the iteration is complete (true or false)}

        const arr = [1.2.3.4.5];
        // Create an iterator to iterate over the array
        const iterator = {
            i: 0.// Index of the current array
            next() {
                var result = {
                    value: arr[this.i],
                    done: this.i >= arr.length   // The iteration completes when true
                }
                this.i++;
                return result
            }
        }
Copy the code

iterable

Iterables have a Symbol. Iterator. The for of loop is used to iterate over the iterable

     // Manually create an iterable
        var obj = {
            [Symbol.iterator]() {
                return {
                    next() {
                        return {
                            value: 1.done: false
                        }
                    }
                }
            }
        }
Copy the code
        const arr = [1.2.3.4];   // An array is an iterable
        const iterator = arr[Symbol.iterator]();
        let result = iterator.next();
        while(! result.done) {const item = result.value;
            console.log(item);        // 1, 2, 3, 4
            result = iterator.next()
        }
        // The code equivalent to the above effect is as follows, for of equals syntax sugar
         for (const item of arr) {
            console.log(item)    // 1, 2, 3, 4
        }
Copy the code

The Generator Generator

A generator is both an iterator and an iterable

    // Write a generator function function followed by a *
        function* method() {
            // Inside the generator is to provide iteration data to the generator
            // Each call to the generator's next method causes the generator function to run to the next yield keyword
            // The yield keyword can only be used inside a generator function to produce an iteration
            console.log('First run')
            let info = yield 1;
            console.log(info + 'Parameters passed from next')
            console.log('The second time')
            yield 2;
            console.log('Third time')
            return 'Value returned when done is true at the end of the first iteration'
        }
        const generator = method(); // Note that this step does not execute method, just an iterator
Copy the code

Implement async await based on Generator

 // Implement async await effect with generator
       function* task() {
            const d = yield 1;
            console.log(d)    / / 1
            const resp = yield fetch("http://localhost:8080/test", {
                method: 'GET'
            });   
            // console.log(resp) Asynchronously requests the result returned by the server
        }
        run(task)

        function run(generatorFunc) {
            const generator = generatorFunc();
            let result = generator.next(); // Start the task (start the iteration) and get the iteration data
            handleResult()
                // Process result
            function handleResult() {
                if (result.done) {
                    return // The iteration is complete
                }
                // The data that did not complete the iteration could be a Promise or other data
                if (typeof result.value.then == 'function') {
                    / / asynchronous
                    result.value.then(data= > {
                        result = generator.next(data)
                        handleResult()
                    }, err= > {
                        result = generator.throw(err)
                        handleResult()
                    })
                } else {
                    / / synchronize
                    result = generator.next(result.value)
                    handleResult()
                }
            }
        }
Copy the code