[ES6 Knowledge] Async functions and elegant code writing

1. async function

1.1 What is async function?

In a word, it is syntactic sugar for the Generator function. Keywords related to asynchronous operations introduced only in ES7.

Native JavaScript Case Collection
JavaScript +DOM Basics
JavaScript Basics to Advanced
Canvas Game Development

Code for the Generator function to read two files:

const fs = require('fs');

const readFile = function (fileName) {
  return new Promise(function (resolve, reject) {
    fs.readFile(fileName, function(error, data) {
      if (error) return reject(error);
      resolve(data);
    });
  });
};

const gen = function* () {
  const f1 = yield readFile('/etc/fstab');
  const f2 = yield readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};

The function of the above codegen can be written asasync function, which is as follows:

const asyncReadFile = async function () {
  const f1 = await readFile('/etc/fstab');
  const f2 = await readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};

After comparison, you will find that the async function replaces the asterisk (*) of the Generator function with async , replace yield with await, and that’s it.

1.2 Basic usage

asyncThe function returns a Promise object, and you can use the then method to add a callback function. When the function is executed, once it encounters await, it will return first, wait until the asynchronous operation is completed, and then execute the subsequent statements in the function body.

awaitThe operator is used to wait for a Promise object, which can only be used inside an async function.

async function getStockPriceByName(name) {
  const symbol = await getStockSymbol(name);
  const stockPrice = await getStockPrice(symbol);
  return stockPrice;
}

getStockPriceByName('goog').then(function (result) {
  console.log(result);
});
function testAwait(){
   return new Promise((resolve) => {
       setTimeout(function(){
          console.log("testAwait");
          resolve();
       }, 1000);
   });
}
 
async function helloAsync(){
   await testAwait();
   console.log("helloAsync");
 }
helloAsync();
// testAwait
// helloAsync

2. Elegant writing of code

2.1 nullish null value coalescing operator “??”

The null value coalescing operator (??) is a logical operator that returns the right operand when the left operand is null or undefined, otherwise it returns the left operand.

function nullish() {
    
    
        // 左侧为 null 或者 undefined 返回 ?? 右侧的值
        let maybeSomething;

        // 未优化前
        // if(maybeSomething){
    
    
        //   console.log(maybeSomething)
        // } else {
    
    
        //   console.log("Nothing found")
        // }

        console.log(maybeSomething ?? "Nothing found"); // 'Nothing found'

        // 不同于 || ,当左侧为一个假值如 "" 或 0 时,返回 ?? 左侧的值
        maybeSomething = false;
        console.log(maybeSomething ?? 200); // false
}

2.2 Optional chaining to prevent crashes

Optional Chaining: Optional Chaining Operator The Optional Chaining Operator is a new JavaScript API that allows reading the value of a deep property of a connected object without explicitly verifying the validity of each reference in the chain.

function optChain() {
    
    
        const student = {
    
    
            name: "Matt",
            age: 27,
            address: {
    
    
                state: "New York"
            },
        };
        // 未优化前
        // console.log(student && student.address && student.address.ZIPCode); 
        // 优化代码
        // console.log(student?.address);//{state: "New York"}
        console.log(student?.address?.ZIPCode);
},

Using optional chaining, you can directly determine whether the object on the left is null or undefined during the chain call. If it is, it will no longer continue the operation, but will return undefined. If not, continue the operation.

2.3 Destructuring assignment

Use destructuring to split values ​​from an array. There is no need for third-party variables to complete the value exchange, which is convenient and concise.

function valReplace() {
    
    
        let x = 1;
        let y = 2;


        // 优化前
        // let temp = x;
        // x = y;
        // y = temp;

        // 利用 ES6 解构优化
        [x, y] = [y, x]
        console.log("x:", x, "y:", y); //x: 2 y: 1
}
function allocated() {
    
    
        // 变量应用
        let num1, num2;
        // 传统写法
        num1 = 10;
        num2 = 100;
        // 使用解构语法在一行中分配多个值
        [num1, num2] = [10, 100];

        // 对象应用
        let student = {
    
    
            name: "Matt",
            age: 29,
        };
        // 传统写法
        let name = student.name;
        let age = student.age;
        // 解构语法赋值
        let {
    
    
            name,
            age
        } = student;
}

2.4 Convert any value to Boolean

The double exclamation mark operator converts other types of values ​​into Boolean values.

function typeCast() {
    
    
        // 使用 Boolean 包装类
        Boolean(0)
        Boolean([])
        Boolean("")
        Boolean({
    
    })

        // 在 JavaScript 中,你可以使用 !! 在 JS 中将任何内容转换为布尔值
        !!true // true
        !!2 // true
        !![] // true
        !!"Test" // true
        !!false // false
        !!0 // false
        !!"" // false
 }

2.5 Array combination merging

Using the spread operator can quickly expand and merge arrays, which is fast and efficient.

function arrConcat() {
    
    
        const nums1 = [1, 2, 3];
        const nums2 = [4, 5, 6];
        // concat 方法
        let newArray = nums1.concat(nums2);
        // 使用扩展运算符组合两个数组
        newArray = [...nums1, ...nums2];

        // 代替将值推送到数组
        let numbers = [1, 2, 3];
        // push 方法追加内容
        numbers.push(4);
        numbers.push(5);
        // 利用扩展运算符处理
        numbers = [...numbers, 4, 5];
}

2.6 Provide default values ​​for function parameters

function defaultArgs() {
    
    
        // 传统写法
        // function pickUp(fruit) {
    
    
        // 	if (fruit === undefined) {
    
    
        // 		console.log("I picked up a Banana");
        // 	} else {
    
    
        // 		console.log(`I picked up a ${fruit}`);
        // 	}
        // }

        // 参数提供默认值写法
        function pickUp(fruit = "Banana") {
    
    
            console.log(`I picked up a ${
    
    fruit}`)
        }

        pickUp("Mango"); // -> I picked up a Mango
        pickUp(); // -> I picked up a Banana
    }

2.7 Collect object values ​​into an array

function objectVals() {
    
    
        const info = {
    
    
            name: "Matt",
            country: "Finland",
            age: 35
        };

        // 传统写法
        // let data = [];
        // for (let key in info) {
    
    
        //   data.push(info[key]);
        // }


        // 使用Object.values()将对象的所有值收集到一个新数组中
        const data = Object.values(info);
}

2.7 Compress multiple conditions

function compCres() {
    
    
        const num = 1;

        // 传统的通过长 || 检查多个条件链
        // if(num == 1 || num == 2 || num == 3){
    
    
        //   console.log("Yay");
        // }

        // 使用 includes() 方法压缩条件链
        if ([1, 2, 3].includes(num)) {
    
    
            console.log("Yay");
        }
}

Exponential operator

function exponent() {
    
    
        // 求幂的传统写法使用 Math.pow()
        Math.pow(4, 2); // 16
        Math.pow(2, 3); // 8
        // ** 指数运算符写法
        4 ** 2 // 16
        2 ** 3 // 8


        // 向下取整传统写法 Math.floor()
        Math.floor(5.25) // -> 5.0
            // ~~  Math.floor()简写运算符
            ~~5.25 // -> 5.0
}

three,

3.1 Modularity

  • rear end
  • NodeJs => CommonJS specification
  • client
    • "CommonJS" => AMD specification

    • AMD: Asynchronous Module Definition asynchronous module definition

      • define(moduleName,[module],factory); define module
      • require([module],callback); introduce module
      • RequireJS is an implementation of the AMD specification
    • CMD specification: Alibaba contributes to modularity

      • Common Module Definition Common Module Definition
      • define(function(require,exports,module){…}) defines the module (module owner)

      seajs.use([module path],function(moduleA,moduleB,moduleC){…}) Using modules
      is essentially different from CommonJS and AMD specifications: CMD specifications follow Rely on nearby and on-demand loading, while the first two rely on front-loading

ES official authority => ES6 modularity

Asynchronous Module Definition Asynchronous module definition

import module from ‘module path’; import module

export module; export module

the difference:

  1. The commonjs module outputs a copy of the value, and the ES6 module outputs a value worth quoting.
  2. The commonjs module is loaded at runtime, and the es6 module (itself a module, but the browser does not support it and requires webpack environment compilation) is loaded at compile time.

3.2 ES6 new feature reference

preview

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/133637531