Advanced usage of ES6 modular and asynchronous programming

Posted by San_John on Thu, 16 Dec 2021 07:57:33 +0100

1, ES6 modularization

1.node.js realize modularization

node.js follows the modular specification of CommonJS. Where: import other modules using the require() method; Module is used by external sharing members of the module Exports object. Advantages of Modularization: reduce the communication cost and greatly facilitate the call between various modules.

2. Classification of front-end modular specifications

Before the birth of ES6 specification, JS has tried and proposed modular specifications such as AMD,CMD and CommomJS** However, these modularities have differences and limitations, and are not the general modular standards for browsers and servers** For example, AMD and CMD are applicable to JS modularization on browser side; CommomJS is suitable for server-side JS modularization.

3. Definitions in ES6 modular specification

1. Each js file is an independent module;
2. Import other module members using the import keyword;
3. Use export to share module members.

4. Basic syntax of ES6 modularization

The modularization of ES6 mainly includes three methods:
1. Default export and default import;
Note: 1 export default can only be used once in each module, otherwise an error will be reported. 2. By default, the name received during import can be any name, as long as it is a legal member name.

//Default export
//Define modular private members
let a = 10;
let b = 10;
//Define modular private method show
function show() { }
// Use the default export syntax of export default to share a and show members outward
export default {
  a,
  show,
};

//Default import
// From 01 Default export js module to import export default members shared externally
import m from "./01.Default export.js";

console.log(m); //Result: {n1: 10, show: [Function: show]}

2. Export and import on demand;
be careful:
Each module can be exported on demand for many times;
The name of the member imported on demand must be consistent with the name exported on demand;
When importing on demand, you can rename using the as keyword;
On demand import can be used with default import.

//Syntax: export members exported on demand
//Export variables a, b as needed
export let a = "0";
export let b = "1";
export function say() {}
//Syntax: import {S1} from 'module identifier'
import info, { a, b, say } from "./03.Export on demand.js";
console.log(a);//0
console.log(b);//1
console.log(say)//[Function: say]
console.log(info)//{ c: 20 }

3. Directly import and execute the code in the module.
If you only want to execute the code in a module, you don't need to get the shared members in the module. At this point, you can import and execute the module code directly.

for (let i = 0; i < 3; i++) {
  console.log(i)
}
// Import and execute directly
import "./05.Run the code in the module directly.js";

2, Promise

1. Callback hell

The nesting of multi-layer callback functions forms a callback hell.
Disadvantages: 1 Code coupling is too strong to maintain; 2. A large number of redundant codes are nested with each other, and the code readability becomes poor.
Solution: Promise added in ES6.

2. Basic concepts

1. Promise is a constructor: we can create an instance of promise const p = new Promise(). The promise instance object from new represents an asynchronous operation. 2.Promise. The prototype contains a then() method: every time the instance object obtained by the new promise () constructor can be accessed through the prototype chain then() method, such as p.then(). 3. . The then() method is used to specify the successful and failed callback functions in advance: p.then (successful callback function, failed callback function), p.then (result = > {}, error = > {}), call When using the then() method, the successful callback function is required and the failed callback function is optional.

3. Reading file content based on then FS

Install then FS, a third-party package, to enable us to read the contents of the file based on Promise:

//Run command
npm i then-fs

3.1 basic use of then FS

Call the readFile() method provided by then fs to asynchronously read the contents of the file, and its return value is the Promise instance object. because
This can be called The then() method specifies the callback function after success and failure for each Promise asynchronous operation. The example code is as follows:

import thenFs from "then-fs";
thenFs.readFile("./files/1.txt", "utf8").then((r1) => {
  console.log(r1);
});
thenFs.readFile("./files/2.txt", "utf8").then((r1) => {
  console.log(r1);
});
thenFs.readFile("./files/3.txt", "utf8").then((r1) => {
  console.log(r1);
});

. If a new Promise instance object is returned in the then() method, you can use the next then() continues processing. through
Yes The chain call of then() method solves the problem of callback hell

3.2,. Catch catch error

If an error occurs in Promise's chain operation, Promise. Com can be used prototype. Catch method for capture and processing; If you don't want the previous error to lead to subsequent errors If then cannot execute normally, you can set Call ahead of catch: (example:)

import thenFs from "then-fs";
thenFs
  .readFile("./files/11.txt", "utf8") //Return promise object
  //Catch errors and output. The error is handled in time without affecting the follow-up then execution
  .catch((err) => console.log(err))
  .then((r1) => {
    console.log(r1);
    return thenFs.readFile("./files/2.txt", "utf8");
  })
  .then((r2) => {
    console.log(r2);
    return thenFs.readFile("./files/3.txt", "utf8");
  })
  .then((r3) => {
    console.log(r3);
    return "00"; //character string
  })
  .then((r4) => {
    console.log(r4);
  });
  //At the end, catch the error and output it. Affect follow-up then execution
// .catch((err) => console.log(err));

3.3, Promise.race() method

Promise. The race () method will initiate parallel promise asynchronous operations. As long as any asynchronous operation is completed, the next step will be executed immediately.
. then operation (racing mechanism)

import thenFs from "then-fs";
const promiseArr = [
  thenFs.readFile("./files/1.txt", "utf8"),
  thenFs.readFile("./files/2.txt", "utf8"),
  thenFs.readFile("./files/3.txt", "utf8"),
];
// Only one result is returned
 Promise.race(promiseArr).then((result) => {
  console.log(result);
 });
// Return all results
Promise.all(promiseArr).then((result) => {
  console.log(result);
});

4. Method of reading file based on Promise package

Packaging requirements of the method:
1. The method name should be defined as getfile;
2. The method receives a formal parameter fpath indicating the file path to be read;
3. The return value of the method is Promise instance object.

Call the resolve and reject callback functions:

import fs from "fs";
function getFile(fpath) {
  return new Promise((resolve, rejects) => {
    fs.readFile(fpath, "utf-8", (err, data) => {
      if (err) {
        return rejects(err);//Failed to read, calling failed callback function
      }
      resolve(data);//After reading successfully, call the successful callback function
    });
  });
}

getFile("./files/11.txt")
  // . Then ((R1) = > {'successful callback function', 'failed callback function')
  .then(
    (r1) => {
      console.log(r1);
    },
    (err) => {
      console.log(err.message);
    }
  );

New Promise() in the code just creates a formal asynchronous operation. To create a specific asynchronous operation, you need to pass a function function in the new Promise() constructor and define the specific operation inside the function function The successful and failed callback functions specified by then() can be received in the formal parameters of function; As a result of Promise asynchronous operation, you can call the resolve or reject callback function to wake up.

3, async/await

1. What is async/await

async/await is a new syntax introduced by ES8 to simplify Promise operation steps. Before async/await, developers could only use chain The method of then() handles Promise asynchronous operations.
Note: 1 If await is used in function, the function must be modified by async. 2. In async method, the code after the first await will be executed asynchronously.

import thenFs from "then-fs";
console.log("A");
async function getFileAll() {
  console.log("B");
  const r1 = await thenFs.readFile("./files/1.txt", "utf8");
  console.log(r1);
  console.log("C");
}
getFileAll();
console.log("D");
/* Execution results:
A
B
D
111
C
*/

4, Eventloop

1. Synchronous task, asynchronous task, EventLoop (event loop)

In order to prevent a time-consuming task from causing the program to fake death, JavaScript divides the tasks to be executed into two categories:
synchronous task: also called non time consuming task, it refers to those tasks queued for execution on the main thread. The latter task can be executed only after the previous task is executed.
Asynchronous task: also known as time-consuming task, the asynchronous task is delegated by JavaScript to the host environment for execution; when the asynchronous task is completed, the JavaScript main thread will be notified to execute the callback function of the asynchronous task.
EventLoop: the JavaScript main thread reads the callback function of asynchronous tasks from the "task queue" and puts it into the execution stack for execution in turn. This process is endless, so the whole operation mechanism is also called EventLoop.

5, Macro and micro tasks

1. What are macro tasks and micro tasks

JavaScript further divides asynchronous tasks into two categories:
Macro task: asynchronous Ajax request, setTimeout, setInterval, file operation and other red tasks. After each macro task is executed, it will check whether there are micro tasks to be executed. If so, it will continue to execute the next macro task after all micro tasks are executed.
microtask: Promise.then,. catch,. finally, process.nextTick, and other microtasks.

Topics: Javascript Front-end Vue.js