Passing friends, you can click a like, pay attention to ~~~

The development history of JS asynchronous solution:

The callback function — — — — — > peomise — — — — — – > the generator + co — — — — — > async + await

1. Solution callback function

Callback functions can solve the asynchronous problem, but there are two types of callback functions: synchronous and asynchronous:

1.2 Callback functions can solve the asynchronous problem

callback

The callback function itself is what we call it by convention, we define it, but we don’t execute it ourselves, it gets executed by someone else.

Advantages: Easy to understand; Disadvantages: 1. High coupling, difficult maintenance, callback hell; 2. Only one callback function can be specified for each task. 3. If several asynchronous operations are not performed in sequence, perform the next operation after the previous operation is completed.

Below is a callback to hell

2. Use of the promise of solutions

2.1 Definition of Promise

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events.

reference

  • Promisra + Usage specifications

To understand:

  • Without asynchrony, promises are not needed.
  • Promises aren’t asynchronous per se, just a way for us to write asynchronous code

2.2 Specification of Promise

When Es6 incorporated promises into its specification, it followed A corresponding standard – the Promise A+ specification.

It is summarized as specification 4321

4:4 Big terms 3:3 states 2:2 events 1:1 objects

2.2.1 Four terms

  1. Fulfill (fulfill) : a set of operations such as state changes and callback execution that occur when a promise succeeds. Although fulfill is adopted as fulfill, resolve is adopted as fulfill in later generations.

  2. Reject: A sequence of actions that occurs when a promise fails.

  3. Eventual Value: The so-called final value refers to the value transferred to the solution callback when the promise is solved. Since the promise has the characteristics of one-off, when this value is passed, it marks the end of the promise waiting state, so it is called the final value, sometimes directly referred to as value.

  4. Reason: The rejection reason, the value passed to the rejection callback when a promise is rejected.

2.2.2 Three states

  • Pending state
  • This is a big pity.
  • (Rejected)

When a promise is in the wait state, it must meet the following conditions:

  • You can migrate to the execute or reject state

This is a big pity.

In the execution state, a promise must satisfy the following conditions:

  • You cannot migrate to any other state
  • You must have an immutable end value

(Rejected)

In the rejection state, a promise must satisfy the following conditions:

  • You cannot migrate to any other state
  • There must be an immutable cause

2.2.3 Two types of events

For the three states, there are only the following two conversion directions:

  • Pending – > fulfilled
  • Pendeing – > the rejected

When the state transitions, events are emitted.

If it is Pending — > Fulfiied, onFulFilled event will be triggered. If it is Pendeing — > Rejected, onFulFilled event will be triggered

2.2.4 One Object

This is a promise object

2.3 Basic usage of Promise

2.3.1 Basic Usage

let p = new Promise(function (resolve,reject) {
            reject("no");
        })
        console.log('p :', p);
Copy the code

The two arguments in the callback function are used to transition the state:

Resolve, select state from PENDING — > fullFilled Reject, select state from Pending — > Rejected

2.3.2 then method

When the state transitions, events are emitted.

Ondepressing event will be triggered if it is pending — > FulfiIED

If it is Pendeing — > Rejected, the onRejected event is triggered

For registration of events, the Promise object provides then methods, as follows:

2.3.3 Typical definition of Promise

2.3.3.1 Case 1: Reading a File

const fs = require("fs");

let p = new Promise(function (resolve,reject) {
    fs.readFile("03 - based/js a.t xt." "."utf8",(err,date)=>{
        if(err){
            reject(err);
        }else{ resolve(date); }}); }); p.then(result= >{
      console.log('result :', result);
  }).catch(err= >{
      console.log('err :', err);
  });
Copy the code

2.3.3.2 Case 2: Return results based on random numbers

let p = new Promise((resolve,reject) = >{
    setTimeout((a)= >{
        let num = Math.random();
        if(num>0.5){
            resolve("success");
        }else{
            reject("fail"); }},1000);
});

p.then(result= >{
    console.log('result :', result);
},err=>{
    console.log('err :', err);
})
Copy the code

2.3.3.3 Reading File encapsulation

const fs = require("fs");

function readFile(file){
    return new Promise((resolve,reject) = >{
        fs.readFile("file"."utf8",(err,date)=>{
            if(err){
                reject(err);
            }else{ resolve(date); }}); }); } readFile("a.txt").then(result= >{
    console.log('result :', result);
},err=>{
    console.log('err :', err);
})
Copy the code

2.3.4 All and race methods

-Serena: Well, it’s not all about success or failure.

Both All and Race are static methods of the Promise constructor object. Call directly with Promise as follows:

  • Promise. All ()
  • Promise. Reace ()
    • The return value is zeropromiseObject.

When you have multiple asynchronous operations, you often have two requirements :(somewhat similar to the logic and logic or in operators)

  1. Ensure that all asynchronous operations are complete before an operation, if only one failure, do not proceed

  2. Whenever there is an asynchronous operation article, an operation is performed in it.

Use all as follows

If there are any errors, see below

Note:

The all method returns true only if all asynchrons are correct, false when one of them fails, and throws the first error message

The use of the fax

Note:

The reac method returns the fastest result in a promise.Race ([P1, P2, p3]), regardless of whether the result itself is a success or a failure.

2.4 Use the third-party Promise library

For third-party Promise libraries, there are two well-known libraries:

  • bluebird
  • q.js

Take Bluebird as an example to demonstrate its usage on the server side.

The first step is installation

Step two, use

2.5 Write the most complete version of the Promise principle

I have gradually encapsulated the basic version of promise, the upgraded version of promise and the complete version of promise in Github, so that I can enter the more hierarchical learning principle in Github.

Making address: github.com/quyuandong/…

3. Generator and CO of the solution

3.1 Emergence of the Generator

ES6 has a new addition: Generators. A generator is a function from which you can exit and re-enter later. The generator’s environment (bound variables) is saved after each execution and can be used the next time it enters

3.2 Use of the Generator

The definition of a generator is similar to that of a normal function, except that an asterisk is added, for example: function * g() {// define an empty generator}. The yield keyword is one of the highlights of Generator functions (only available in Generator functions, not normal functions). It literally means “yield” and produces a result each time a program executes to yield.

The words “Generator” and “yield” are used figuratively enough. The Generator is like a factory that produces something whenever the consumer needs it and returns it to the consumer.

Example:

3.3 Execution mode of the Generator

3.4 Work with Generator, Promise, and CO

Co library address: github.com/tj/co

$ npm install co

4. Async and await of solution

Async /await is an optimization of Promise: Async /await is based on Promise and is a further optimization, but when writing code, the Promise API itself appears very little, very close to synchronous code writing;

4.1 Async Keyword

  • 1) Indicates that there may be an asynchronous process in the program:
    • It can have the await keyword inside; It can also be none (not fully synchronized);
  • 2) Non-blocking:
    • If there is an asynchronous process inside an async function, it will wait, but the async function itself will return immediately and will not block the current thread. The asynchronous process inside an async function modified with await keyword, working on the corresponding coroutine, will block waiting for the completion of the asynchronous task before returning.
  • 3) Async function returns a Promise object:
  • 4) No waiting
    • An async function is executed without await, and it executes immediately, returning a Promise object,

4.2 await keyword

  • 1) Await can only be used inside async functions: cannot be placed inside normal functions, otherwise an error will be reported;

  • 2) Await keyword followed by Promise object: in Pending state, corresponding coroutine will hand over control and enter wait state, which is the essence of coroutine;

  • 3) await async wait: resolve(data) message and return data,

  • 4) “await” can also be followed by synchronous code: however, the system will automatically convert it to a Promsie object,

4.3 Simple Use Cases:

The source code

function timeout(ms) {
    return new Promise((resolve, reject) = > {
      setTimeout(resolve, ms, "finish");
    });
  }

  // Asynchronous code
  async function asyncTimeSys(){
      await timeout(1000);
  }

  // Call the method to receive the return value
  asyncTimeSys().then((value) = >{
      console.log(value);
  });
Copy the code