ES7, ES8 knowledge points

Table of contents

Chapter 3 ECMASript 7 New Features

3.1. Array.prototype.includes

3.2. Exponential Operators

Chapter 4 ECMASript 8 New Features

4.1. async and await

4.1.1. async functions

4.1.2. await expressions

4.2. Object.values 和 和 Object.entries

4.3. Object.getOwnPropertyDescriptors


Related video link: Shang Silicon Valley Web front-end ES6 tutorial, covering ES6-ES11_哔哩哔哩_bilibili

Chapter 3 ECMASript 7 New Features


3.1. Array.prototype.includes

The Includes method is used to detect whether an element is contained in the array and returns a Boolean value

const mingzhu = ['西游记','红楼梦','三国演义','水浒传'];

//判断
console.log(mingzhu.includes('西游记'));  //true
console.log(mingzhu.includes('金瓶梅'));  //false

3.2. Exponential Operators

The exponent operator "**" is introduced in ES7 to implement exponentiation, which has the same function as Math.pow

console.log(2 ** 10);  // 1024
console.log(Math.pow(2, 10));   //1024

Chapter 4 ECMASript 8 New Features

4.1. async and await

        The combination of async and await can make asynchronous code look like synchronous code

        Synchronous code in js and heterogeneous code original links:

Synchronous code and asynchronous code in js

        Synchronous code
        The code is executed in a single line. After sending the server request and waiting for the returned data, the webpage will be blank (blocking the operation of the webpage)

        Asynchronous code
        The code continues to execute subsequent code after sending the request, without waiting for the server to return data (the web page runs smoothly)

        Common asynchronous execution codes in js:
        1. ajax request: Asynchronous JavaScript and XML
        2. Timer: It will be executed after a certain period of time.
        3.Event processing function: it will be executed only when the event trigger condition is met

4.1.1. async functions

  1. The return value of the async function is a promise object
  2. The result of the promise object is determined by the return value of the async function execution
async function fn(){
    // 返回一个字符串
    return '尚硅谷';
}
const result = fn();
console.log(result);

//结果:
//Promise
//[[Prototype]]: Promise
//[[PromiseState]]: "fulfilled"
//[[PromiseResult]]: "尚硅谷"


//返回的结果不是一个 Promise 类型的对象, 返回的结果就是成功 Promise 对象
async function fn(){
    return;
}
const result = fn();
console.log(result);
//结果:
//Promise {<fulfilled>: undefined}
//[[Prototype]]: Promise
//[[PromiseState]]: "fulfilled"
//[[PromiseResult]]: undefined

        

        An error is thrown, and the returned result is a failed Promise 

async function fn(){
    throw new Error('出错啦!');
}
const result = fn();
console.log(result);
//会报错

       

         If the returned result is a Promise object 

async function fn(){
    
    return new Promise((resolve, reject)=>{
        resolve('成功的数据');   //成功的数据
        // reject("失败的错误");  //失败的错误,会报错
            });
}
const result = fn();
console.log(result);

        

        call the then method

    async function fn(){

            return new Promise((resolve, reject)=>{
                resolve('成功的数据');  //成功的数据
                // reject("失败的错误");  //出现警告:失败的错误
            });
    }
    const result = fn();
    console.log(result);

    result.then(value => {
        console.log(value);
    }, reason => {
        console.warn(reason);
    })

4.1.2. await expressions

  1. await must be written in an async function
  2. The expression on the right side of await is generally a promise object
  3. await returns the value of promise success
  4. If the promise of await fails, an exception will be thrown, which needs to be captured and processed by try...catch
        //创建 promise 对象
        const p = new Promise((resolve, reject) => {
            // resolve("用户数据");  //结果:用户数据
            reject("失败啦!");  //失败啦!
        })

        // await 要放在 async 函数中.
        async function main() {
            try {
                let result = await p;
                //
                console.log(result);
            } catch (e) {
                console.log(e);
            }
        }
        //调用函数
        main();

        Combining aysnc and await to read files

//1. 引入 fs 模块
const fs = require("fs");

//读取『为学』
function readWeiXue() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/为学.md", (err, data) => {
            //如果失败
            if (err) reject(err);
            //如果成功
            resolve(data);
        })
    })
}

function readChaYangShi() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/插秧诗.md", (err, data) => {
            //如果失败
            if (err) reject(err);
            //如果成功
            resolve(data);
        })
    })
}

function readGuanShu() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/观书有感.md", (err, data) => {
            //如果失败
            if (err) reject(err);
            //如果成功
            resolve(data);
        })
    })
}

//声明一个 async 函数
async function main(){
    //获取为学内容
    let weixue = await readWeiXue();
    //获取插秧诗内容
    let chayang = await readChaYangShi();
    // 获取观书有感
    let guanshu = await readGuanShu();

    console.log(weixue.toString());
    console.log(chayang.toString());
    console.log(guanshu.toString());
}

main();

        async and await encapsulate AJAX requests:

        // 发送 AJAX 请求, 返回的结果是 Promise 对象
        function sendAJAX(url) {
            return new Promise((resolve, reject) => {
                //1. 创建对象
                const x = new XMLHttpRequest();

                //2. 初始化
                x.open('GET', url);

                //3. 发送
                x.send();

                //4. 事件绑定
                x.onreadystatechange = function () {
                    if (x.readyState === 4) {
                        if (x.status >= 200 && x.status < 300) {
                            //成功啦
                            resolve(x.response);
                        }else{
                            //如果失败
                            reject(x.status);
                        }
                    }
                }
            })
        }
    
        //promise then 方法测试
        // sendAJAX("https://api.apiopen.top/getJoke").then(value=>{
        //     console.log(value);
        // }, reason=>{})
  
        // async 与 await 测试  axios
        async function main(){
            //发送 AJAX 请求
            let result = await sendAJAX("https://api.apiopen.top/getJoke");
            //再次测试
            let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')

            console.log(tianqi);
        }

        main();

4.2. Object.values 和 和 Object.entries

  1. The Object.values() method returns an array of all enumerable property values ​​for a given object
  2. The Object.entries() method returns an array of traversable properties [key, value] for a given object itself

4.3. Object.getOwnPropertyDescriptors

  • This method returns a description object of all the properties of the specified object
//声明对象
const school = {
    name:"尚硅谷",
    cities:['北京','上海','深圳'],
    xueke: ['前端','Java','大数据','运维']
};
//获取对象所有的键
console.log(Object.keys(school));
//获取对象所有的值
console.log(Object.values(school));
//entries,返回的是一个数组,该数组每个元素也是一个数组[键,值]
console.log(Object.entries(school));
//创建 Map
const m = new Map(Object.entries(school));
console.log(m.get('cities'));
//对象属性的描述对象
console.log(Object.getOwnPropertyDescriptors(school));

//getOwnPropertyDescriptors获取的是name里面的内容
const obj = Object.create(null, {
        name: {
            //设置值
            value: '尚硅谷',
            //属性特性
            writable: true,
            configurable: true,
            enumerable: true
        } 
});

Guess you like

Origin blog.csdn.net/woai_mihoutao/article/details/123919722