ES6 study notes 3 async/await/Symbol/Iterators/Generator/Proxy

async asynchronous and await waiting

The async function returns a Promise object, and a callback function can be added using the then method.

 	async function hi() {
    
    
        return "hi";
    }
    hi().then(res => console.log(res));//hi

There may be an await expression in the async function. When the async function is executed, if an await is encountered, the execution will be suspended first. After the triggered asynchronous operation is completed, the execution of the async function will be resumed and the parsed value will be returned.

function say(msg, time) {
    
    
        return new Promise((resolue, reject) => {
    
    
            setTimeout(() =>
                resolue(msg), time);
        })
    }
    async function doit() {
    
    
        var s1 = await say("你好...", 2000);
        console.log(s1);
        var s2 = await say("呀!", 3000);
        console.log(s2);
        return s1 + s2;
    }
    doit().then(res => console.log(res));

After waiting for 2 seconds, output "Hello...", and after waiting for 3 seconds, output "Ah!" and "Hello...Ah!" at the same time. Note
The result of running the above code
: the await keyword is only valid in async function. If you use await outside the body of an async function, you'll just get a syntax error

Symbol

Symbol is a new value data type. Its value is unique and immutable . It is often used as a unique key or identifier
eg:

	var sym = Symbol( "符号" );
	console.log(typeof sym); // symbol
	var obj = {
    
    
        sym: "abc"
    };

The new operator cannot be used in front of Symbol here .
If it is used as a property of an object, the property will be non- enumerable

Iterators Iterators

The iterator allows one element of the data collection to be accessed at a time. When the pointer points to the last element of the data collection, the iterator will exit. **It provides the next() function to traverse a sequence, this method returns an object containing done and value properties.
Iterable objects all have iterators (objects that can be traversed by for are all iterable objects: String, Array, Set, Map)

 	var arr = [2, 4, 5, 6];
    var iter = arr[Symbol.iterator]();
    console.log(iter.next()); //{value: 2, done: false}
    console.log(iter.next()); //{value: 4, done: false}
    console.log(iter.next()); //{value: 5, done: false}
    console.log(iter.next()); //{value: 6, done: false}
    console.log(iter.next()); //{value: undefined, done: true}

For of traversal uses iterators

    var arr = [2, 4, 5, 6];
    var iter = arr[Symbol.iterator]();
    console.log(iter.next()); 
    for (let i of iter) {
    
    
        console.log(i);
    }

This example shows that for of uses iterators.
The result of running the above code

Generator generator

Generator functions are a new feature of ES6 that allow an iterable object returned by a function to generate multiple values.

  • Add * before ordinary functions
  • Control generation through the yield keyword
  • The final function executes, returning an iterable of elements

Each time yield is executed, the returned value becomes the next value of the iterator.

Example 1: Implement the range function, given the range and step size, generate an array that satisfies the conditions

    function* range(start, end, step = 1) {
    
    
        while (start <= end) {
    
    
            yield start;
            start += step;
        }
    }
    var list = range(1, 10, 2);
    var arr = [...list];
    console.log(arr);//[1, 3, 5, 7, 9]

Example 2: Implement randRange(min,max,len) to generate a random iteration object with a length of len

	function* randRange(min, max, len) {
    
    
        for (let i = 0; i < len; i++) {
    
    
            yield Math.round(Math.random() * (max - min)) + min;
        }
    }
    var list = [...randRange(1, 10, 5)];
    console.log(list);//[7, 3, 3, 5, 10]

Proxy proxy

The Proxy object is used to create a proxy of an object, so as to realize the interception and customization of basic operations (such as attribute lookup, assignment, enumeration, function call, etc.). It is a hijacking of the original object operation.

Example: (beggar version two-way binding) input and p two-way binding

    <input type="text" id="inp">
    <p id="myp"></p>
 	var inp = document.getElementById("inp");
    var myp = document.getElementById("myp");
    var obj = {
    
    
        msg: "我喜欢vue"
    };
    var o = new Proxy(obj, {
    
    
        get(target, prop) {
    
    
            return target[prop];
        },
        set(target, prop, value) {
    
    
            if (prop === "msg") {
    
    
                inp.value = value;
                myp.innerText = value;
            }
            target[prop] = value;
        }
    });
    inp.value = o.msg;
    myp.innerText = o.msg;

    inp.oninput = function () {
    
    
        o.msg = this.value;
    }

The result of running the above code

Guess you like

Origin blog.csdn.net/TeAmo__/article/details/123095688