Asynchronous Programming Notes

Keywords: Javascript

Asynchronous programming

catalogue

1, EventLoop

1.JavaScript is a single threaded language

2. Synchronous and asynchronous tasks

3.EventLoop execution process

2, Promise

3, async and await

4, Macro and micro tasks

1, EventLoop

1.JavaScript is a single threaded language

Basic concepts

JavaScript is a single threaded programming language. In other words, you can only do one thing at a time.

Execution flow chart

The problem of single thread executing task queue: if the previous task is very time-consuming, the subsequent tasks have to wait all the time, resulting in the problem of fake death of the program.

2. Synchronous and asynchronous tasks

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 known as non time consuming tasks, these tasks are those queued on the main thread

    • The next task can only be executed after the previous task has been executed

  • asynchronous task

    • Also known as time-consuming tasks, asynchronous tasks are delegated by JavaScript to the host environment (browser nodejs) for execution

    • When the asynchronous task is completed, the JavaScript main thread will be notified to execute the callback function of the asynchronous task

Synchronization code: execute line by line from top - > bottom. The next line must wait for the result of the previous line before executing down

Asynchronous code: use callback functions to receive results

Note: setTimeout itself is synchronous, but the callback function is executed asynchronously

    <script>
        // Synchronization code
        // Concept: execute line by line from top to bottom. The next line must wait for the result of the previous line
        console.log(1);
        if (true){
            console.log(2);
        }
        // The binding is synchronous, and the event handler function executes asynchronously
        document.addEventListener('click', () => {
            console.log(3);
        })
        console.log(4);
        setTimeout(() => {
            console.log(5);
        }, 0)
        console.log(6);
        for (let i = 0; i < 100; i++) {
            console.log("for loop");
        }
        console.log(7);

        // Asynchronous code:
        // SetTimeout (callback function), setinterval (callback function), ajax network request (callback function), event handling function (callback function)
        // Framework: this. $nexttick() - > promise (callback function)
    </script>

 

3.EventLoop execution process

  • Synchronization tasks are executed sequentially by the JavaScript main thread

  • Asynchronous tasks are delegated to the host environment for execution

  • The callback function corresponding to the completed asynchronous task will be added to the task queue for execution

  • After the execution stack of the JavaScript main thread is cleared, the callback functions in the task queue will be read and executed in order

  • The JavaScript main thread repeats step 4 above

Execution stack: used to execute code(

Web APIS: asynchronous code (js code runs in browser environment, calling function in browser to implement asynchronous callback execution).

Task queue: the callback functions in asynchronous tasks are stored in the task queue (put the function body to be executed in asynchronous tasks in the task queue to be executed by the execution stack)

be careful:

Before executing the code, perform function pre parsing and variable pre parsing, and execute the code only after the parsing is completed

All asynchronous tasks are executed only when the execution stack is idle (that is, after the main thread and synchronous code execution are completed)

The JavaScript main thread reads the callback functions of asynchronous tasks from the "task queue" and puts them into the execution stack for execution in turn. This process is endless, so the whole operation mechanism is also called EventLoop (event loop)

Summary: the main execution stack takes tasks from the task queue for execution. Such a loop process is called EventLoop -- showing how asynchronous code executes (event loop)

2, Promise

Concept: Associate (manage - include) the objects of asynchronous tasks and get the success / failure results of asynchronous tasks in the future

 <script>
        console.log(1)
        // Review Promise
        // Concept: Associate (manage - include) the objects of asynchronous tasks and get the success / failure results of asynchronous tasks in the future
        // use:
        // new Promise() is instantiated, and the code in the function body is executed immediately (synchronized)
        let p = new Promise((resolve, reject) => {
            console.log(2)
            // Built in parameters (resolve called - > management task succeeded - > callback function execution in then())
            // Reject() = > management task failed - > callback function execution in catch()
            resolve('success')
            console.log(3);
        })
        console.log(4);
        // p.then().catch() is bound with a function to listen for success / failure results - it will not be executed immediately ("resolve asynchronous")
        p.then(res => {
            console.log(5);
            console.log(res)
        }).catch(err => {
            console.log(6);
            console.log(err)
        })
        console.log(7);
    </script>

 

3, async and await

Basic concepts

Async await is known as the ultimate solution of asynchrony. There is no callback after async await

async/await is a new syntax introduced by ES8 (ECMAScript 2017) to simplify Promise asynchronous operations. Before async/await, developers could only handle Promise asynchronous operations through chained. then().

  • Advantages of. then method:

    • Solved the problem of callback to hell

  • Disadvantages of. then method

    • Code redundancy, poor readability and difficult to understand

 <script>
        // async function + await replaces. then() 
        // new Promise() will immediately execute all the code in the function body
        // resolve() asynchronous
        // Await (the code will be in the async function and wait to stop) - > right combination (execute the code on the right of await first)
        // If you wait, you will continue to execute the code outside async (if there is synchronous code, run again)
        console.log(1)
        function createPromiseObj() {
            console.log(2);
            return new Promise((resolve, reject) => {
                console.log(3)
                resolve('success')
                console.log(4);
            })
            console.log(5);
        }
        console.log(6);
        testOne()
        console.log(7);
        async function testOne() {
            console.log(8);
            const res = await createPromiseObj() 
            console.log(res);
            console.log(9);
        }
        console.log(10);
 </script>

 

  <script>
    console.log(1)
    async function fn () {
      console.log(4)
      const res = await 2
      console.log(res)
    }
    fn()
    console.log(3)
  </script>

The operation results are as follows:

Posted by aboldock on Tue, 26 Oct 2021 03:43:19 -0700