preface

This article is a summary of personal Promise, please correct any mistakes in time!!

Front knowledge

What is Promise?

Promise is a new solution to asynchronous programming that is more powerful than the way callback functions and events were used to resolve asynchronous operations.

What is a callback function?

You can think of it as something to do after you’ve done something, and you need to pass in a function as an argument to do it

What is an event?

An event is simply something that happens and triggers a function accordingly. Of course, an event is also an asynchronous operation that does not execute immediately but waits for some condition to be satisfied

What is callback hell?

An asynchronous operation has to wait for the previous asynchronous operation to complete before it can be executed, and whether you use an event or a callback function, it gets nested, making the code hard to read

Call back the hell demo

Note: The following code is intended to demonstrate callback hell and is not practical

  • Read the file

    TXT contains path2.txt, path2.txt contains paththree. TXT, and to retrieve the contents of pathThree, you need to retrieve the previous contents

// The following code is intended to simulate callback hell
const fs = require("fs");
fs.readFile("./pathOne/pathOne.txt"."utf-8", (err, data) => {
    console.log("pathOne:" + data);
    if(data) {
        fs.readFile(data, "utf-8", (err, data) => {
            console.log("pathTwo:" + data);
            if(data) {
                fs.readFile(data, "utf-8", (err, data) => {
                    console.log(data)
                })
            }
        })
    }
})
Copy the code

  • Ajax simulation callback hell

    To find the girl with ID 3, you need to find the list of classes and see if there are any classes that match, and then send a request to find the data

Note: JQ’s Ajax approach is used for demonstration purposes

  • Event callback hell

    The latter button will bind events only if the former button is clicked

Note: Callback hell may look like a triangle. If you see one, you need to be aware that you are already in callback hell

Event Loops

A brief introduction to a few concepts of the event loop, so that you don’t have to read too much.

Call Stack: An execution environment used to store various statements. Each statement or block is added to the execution stack before the statement is executed, the execution stack is created before the statement is executed, the statement is added, and the execution stack is destroyed

Macrotask Queue: Asynchronous functions such as timer callbacks, event callbacks, etc

Microtask Queue: Callbacks generated by promises are put into this Queue

First perform the contents of the stack, in fact, the script code in the label, it will be in order to perform, if encounter synchronization code will be executed directly, run into the unity of the asynchronous code into the event queue, wait until the execution stack when there are no things, it will first look at the event in the queue queue exists to execute the statement, If it exists, it will be executed first. After all the statements in the micro queue are executed, it will see whether there are statements to be executed in the macro queue, and then take out the macro queue to execute

To see if microqueues are executed earlier than macroqueues, see the following example

Basic use of Promise

Three states

  • Pending: Pending
  • This is a big pity
  • Rejected: It has failed

The characteristics of

The status of an object is not affected

Only Promise can determine the final state, and no manipulation can interfere

State irreversibility

Whenever a state changes, it is already dead and cannot be changed.

We can only push the depressing or pending to the rejected from pending to the depressing and then to the rejected

The basic use

Promise is a constructor that we can use to generate a Promise instance, and that constructor takes as an argument a function that has two arguments, resolve and Reject, that are provided to us by the JS engine

Creating a Promise instance

const promise = new Promise((resolve, reject) = > {
    if(Math.random() < 0.8) {
        resolve("I am so handsome.")}else {
        reject("I'm still handsome."); }})Copy the code
  • The resolve function

    Move the state of the current Promise instance from Pending to Depressing

  • Reject function

    Push the current Promise instance state from Pending to Rejected

Since resolve and reject are both functions, we can pass them an argument as the result of the asynchronous operation. Where do we get the result? To look down

Then method

The then method receives two callback functions as parameters, namely thenable and catchable. Thenable is called when the state is fulfilled, and the catchable function is called when the state is Rejected. And the catchable function is optional

const promise = new Promise((resolve, reject) = > {
    if(Math.random() < 0.5) {
        resolve("fulfilled")}else {
        reject("rejected")	// Usually an exception object Error
    }
})

promise.then(res= > {
    / / thenable function
    console.log(res)
}, err => {
    / / catchable function
    console.log(err)
})
Copy the code

Pay attention to the

  1. Thenable and catchable are asynchronous functions, so they are queued up for execution.

  1. The function in the Promise constructor is a synchronization function that executes immediately

  1. A Promise can correspond to multiple handlers

In the pending phase, an uncaught error or active call to Reject pushes the state to Rejected and is caught by the Catchable

  • Error not caught

  • Capture the error

  • Active call reject

Details added:

try… Catch: only synchronous errors can be caught, but asynchronous errors cannot be caught

Solutions:

  • Asynchronous functions have nested try… catch

  • window.onerror

Serial execution of a Promise

If a later Promise needs to use the results of a previous Promise, you need to make the Promise execute serially

The then or catch methods in a Promise return a brand new Promise object

! [1578323768150](Promise.assets/

New Promise state features

  • If the state of the Promise is pending, the new Promise state is pending

Why is the status of promisE1 pending? A promise that implements resolve will move its state to resolved, but the promise1 state will wait for the promise to complete. Thenable and catchable are asynchronous functions that are added to the event queue, and the log function is executed synchronously. If the log function is not executed, then the processing result is not received. So the state is pending

Myth: With the exception of pending, don’t assume that the state of a previous Promise necessarily determines the state of a newly generated Promise

  • If the current Promise state is Resolved or Rejected, the corresponding subsequent handler functions (thenable or catchable) are run and the return value of the function is applied as state data to the new Promise.

Note that the state of the previous Promise only causes its own then method to execute a function, and does not cause the then method of the next Promise to execute a function. So all Promise states returned by then are resolved

chestnut

What is the output of the following code?

const promise = new Promise((resolve, reject) = > {
    resolve(2)})const promise1 = promise.then(res= > {
    return res * 2
}, err => {
    return err * 3
})
promise1.then(res= > {
    console.log(res * 2)
}, err => {
    console.log(err * 3)})Copy the code
const promise = new Promise((resolve, reject) = > {
    throw Daniel Wu;
})
const promise1 = promise.then(res= > {
    return "Wick good handsome";
}, err => {
    throw `${err}So handsome.;
})
promise1.then(res= > {
    console.log(res)
}, err => {
    console.log(err, 30)})Copy the code
const promise = new Promise((resolve, reject) = > {
    resolve("The cards are on the table.");
})
const promise1 = promise.then(res= > {
    return `${res}In fact, I am Daniel Wu;
}, err => {
    return I'm not Daniel Wu;
})
promise1.then(res= > {
    console.log(res)
}, err => {
    console.log(err)
})
Copy the code
  1. The first is: 8

  1. The second is: Daniel Wu is so handsome

  1. The third is: showdown, in fact, I am Daniel Wu

Solve the callback hell ahead

Read the file

Ajax callback hell

Resolve the callback hell of the event

Promise the related API

Instance members

An instance object created by a Promise can use methods such as THEN and catch directly, indicating that these methods exist on the prototype of the Promise

Promise.prototype.then()

As I said, no more introductions here!

Promise.prototype.catch()

As I said, let’s look at something new here.

Catch is the function that is called when an error occurs and is also an alias of. Then (null/undefined, Rejection)

  1. Wrong “bubble nature”

    Errors bubble backwards until they are caught

  1. It is not recommended to use catch as the second argument to then

Let’s look at a question about Uncaught (in promise)

When a Promise throws an error, it is reported if it is not caught

Now the solution to this problem is to catch the error. Let’s take a look at the following solutions

Then (thenable, catchable)

Method 2: The instance method catch also catches an error

So what’s going on here? Why can’t I catch it? As I said earlier, promises can correspond to multiple handlers, so you caught them in the catch, what about the then? Not really

Add a catch

  1. Eat the wrong

    The error that a Promise throws does not affect the external code, and what should be run will still be run

finally

ES2018 introduced a standard that executes a Promise regardless of its final state, and is related to the order in which finally statements are made. Similar to try… The finally keyword for catch

  • The statement sequence

  • resolved

  • rejected

    The finally method takes no arguments, and thenable and catchable go to finally, and you have no way of knowing their final state

Similarly, finally returns a Promise

Static members

Promise.resolve([args])

Depending on the parameters, the returns will be different

  1. Parameters for the Promise

    Do nothing, return as is

Note: Although you don’t do any processing, the status data is your own

  1. Does not carry a parameter or the parameter is a raw value

    In any case, it’s going to return a Promise object with the Resolved state, and the state data is what we defined, okay

Promise.reject(args)

This method returns a Promise with the Rejected state, and the state data is passed in

Promise.all(iterable)

Takes an iterator (think of it as an array) and returns a new Promise object. Resolve is changed to a Promise object and is in resolved state.

All will return a new Promise object. When will thenable and catchable be triggered for this new Promise object?

According to the different states, there are two cases

  1. When all the Promise instances in the array are in the Resolved state

    When all Promise instances in the array are in resolved state, the Thenable function will be triggered. Thenable is an array of state data for all Promise instances

  1. When the Promise instance in the array is in the Rejected state

    Once rejected is present, the thenable function of All is not triggered. Instead, the Catchable function is triggered. The catchable function takes the state data of the first Promise instance whose Rejected state is present

    Look at the chestnuts. Maybe it’s a little convoluted

Let’s say the error in the array Rejected

If a Promise is stored in an array with a catch of its own, then if something goes wrong, the catch of the all method is not fired. The catch of the all method is triggered only if there is no catch of its own

Promise.race(iterable)

Takes an iterator and returns a Promise object

A race is a running race. At the beginning, everyone is preparing until the whistle blows and someone rushes out first. There must be only one person ahead, so a race will only trigger once. Race’s Thenable or Catchable is then triggered depending on the status

Solve the MySql asynchronous query problem in NodeJS

Execution environment:

The Node v12.13.1

webstorm

Express Setup Service

Situation of problem occurrence:

A few months ago, WHEN I was blogging with Node, I ran into a database query problem. I didn’t think much about it. Just like WHEN I simplify code in Java with selectByWhere(String SQL) or selectOne(Integer), it makes sense to write code that later turns out not to be desirable and doesn’t get the value of the query

So.. I took the following approach (now that I think about it, it’s insane!)

  • Declare a temporary variable outside the query method, assign it to the result of the query (not realizing it was an asynchronous query at the time), and return it as the value of the entire function

    What a hell to have access to data!!

Then I found that mysql is an asynchronous query, so I wrote with async and await. Then this article is about Promise, so I’ll wrap it with Promise and save async and await for the next article

Using Promise packaging, the effect is easy to implement!!

Refer to the article

Deep Understanding of ES6

Nguyen other ES6