First, before introducing ES6 modularity, let’s take a quick look at how es6 modules differ from CommonJS modules

When you learn the JavaScript language, you’ll notice that it has modules in two formats.

One is THE ES6 module, or ESM for short. The other is the CommonJS module for Node.js, or CJS for short.

The CommonJS module uses require() for loading and module.exports, while ES6 uses import and export.

Above, require() loads synchronously, and the rest of the code must wait for this command to complete before executing. Import commands are loaded asynchronously, or more accurately, ES6 modules have a separate static parsing phase where dependency analysis is done and the lowest level module executes first.

1. What is ES6 modularity?

ES6 modular specification is a common modular development specification for browser and server. It has greatly reduced the cost of modular learning for front-end developers, and developers do not need to learn additional modular specifications such as AMD,CMD or CommonJS

As defined in the ES6 modular specification:

  • Each JS file is an independent module
  • Use to import other module membersimportThe keyword
  • For use by external shared module membersexpostThe keyword

2. Prepare for ES6 modularization in Node. js.

Node.js supports only CommonJS modularity by default. To experience and learn ES6 modularity syntax based on Node.js, you can perform the following two steps:

  1. Make sure you have Node.js v14.15.1 or later installed (you can open your terminal and enter)node -vTo query the current version)
  2. Add it to the root node of package.json"type":"module"Node, perform the following operations:

3. Default export and default import.

  • Default export syntax:export defaultMembers exported by default

  • Default import syntax:importReceiving the namefromModular identifier

Note:

  1. Export default can be used only once in each module, otherwise an error will be reported!
  2. The default import accepts any name, as long as it is a valid member name

4. Export on demand versus import on demand.

  • Export on demand syntax:exportMembers exported on demand

  • On-demand import syntax:import{import members on demand}from‘Module Identifier’

Matters needing attention:

  1. Available in each moduleMany timesOn-demand export
  2. On demandThe name of the imported memberMust andThe name of the export on demandconsistent
  3. It can be used when importing on demandThe as keywordRename
  4. On-demand imports can be used with default imports, for example:

5. Import and execute the code directly.

If you just want to execute the code in a module, you don’t need to get the outward shared members of the modularity. In this case, you can directly import and execute the model airplane, as shown in the following example:

On the terminal, you can just print out 0,1,2

6.Promise

1.PromiseWhat is?

  • It is mainly used for asynchronous computing
  • Asynchronous operations can be queued, executed in the desired order, and returned as expected
  • Promises can be passed and manipulated between objects to help us deal with queues

2.Promise:

In general, we don’t see a lot of callback nesting, usually one or two levels, but in some cases, when a lot of callback nesting, the code can be very cumbersome, which can cause a lot of trouble in our programming. This situation is commonly known as callback hell. And that’s where our Promise came in

Promises are designed to solve two problems:

  • Callback hell, code is difficult to maintain, often the output of the first function is the input of the second function
  • Promises can support multiple concurrent requests, retrieving data from concurrent requests
  • This Promise solves the problem of asynchrony, not asynchrony by itself

3. Basic concepts of Promise:

1.Promise is a constructor

  • We can create an instance of the Promiseconst=new Promise
  • Promise instance object that comes out of new,Represents an asynchronous operation

2.Promise.prototype contains a. Then () method

  • Each time the new Promise() constructor gets an instance object
  • Can beBy way of the prototype chainAccess the.then() method, for examplep.then()

3. The then() method is used to pre-specify successful and failed callback functions

  • p.then(Successful callback, failed callback)
  • p.then(result= > {},err> {})
  • When the.then() method is called, the successful callback is mandatory and the failed callback is optional

4.Promise:

. Then () method

The fs module officially provided by Node.js only supports the callback function to read the file, and does not support the call method of Promise. Therefore, run the following command to install the then-fs third-party package

npm i then-fs
Copy the code

Once installed, the readFile() method provided by THEN-fs is called to read the contents of the file asynchronously, and its return value is an instance object of Promise. The.then() method can therefore be called to specify successful and failed callback functions for each Promise asynchronous operation in the following format:

Properties of the.then() method

If a new Promise instance object is returned from the previous then() method, processing can continue with the next.then(). The problem of callback hell is solved by chain calls to the.then() method

The catch () method

If an error occurs during the chain operation of a Promise, the promise.prototype. catch method can be used to catch and handle it. Code examples:

thenFs.readFile('./files/11.txt,utf8')// There is no file read failure
.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)
})
.catch(err= >{ // Use the.catch() method to catch the error at line 1 and print the error message
  console.log(err.message)
})
Copy the code

Promise. All () method:

The promise.all () method initiates parallel asynchronous Promise operations and waits for all asynchronous operations to complete before performing the next.then operation (wait mechanism). Example code is as follows:

7.async/await

1. What is async/await?

Async /await is a new syntax introduced in ES8 to simplify Promise asynchronous operations. Before async/await, developers could only handle Promise asynchronous operations in chain-.then () mode, which solved the problem of callback hell, but also made code redundant, poorly read, and difficult to understand

Contrast async/await with.then() :

.then():

async/await:

In addition, there are two points to note when using async/await:

  • If await is used in function, functionMust beIs decorated async
  • In the async method,The code before the first await is executed synchronouslyThe code after await will be executed asynchronously