JavaScript Asynchronous Programming

1. Synchronization mode

Synchronous mode means that the tasks in our code are executed sequentially, and the program is executed in the order in which the code was written.

The following code is the code for synchronous mode, and its execution sequence is analyzed in detail

console.log('Global begin')

function bar() {
    console.log('Bar task')}function foo() {
    console.log('Foo task')
    bar()
}

foo()
console.log('Global end')

// Global begin
// Foo task
// Bar task
// Global end
Copy the code

Analysis:

  • First, analyze the code structure. This code is in synchronous mode. When js reads the code, it first puts an (anonymous) anonymous function on the call stack.

  • When the first line console.log(‘Global begin’) is read, it is pushed onto the call stack and then executed. When the console prints the result, it is popped off the call stack and continues to the next line of code.

  • When the function bar and function foo are read, there is no execution task in the call stack because they are not executed.

  • When a call to foo() is read, foo() is first pushed onto the call stack, and the console.log(‘ foo task’) code is pushed onto the call stack, and the call stack is popped after execution. Then bar() is pushed onto the call stack, the program goes to the internal parsing function bar(), and console.log(‘ bar task’) is pushed onto the call stack. After foo() is executed, pop the function bar() and foo() off the call stack;

  • Finally, the console.log(‘Global end’) is pushed onto the call stack and executed, then it is ejected, the code is run, the (anonymous) is ejected from the call stack, and the program is completely finished.

2. Asynchronous mode

On the browser side, long operations should be performed asynchronously to avoid browser unresponsiveness. The best example is Ajax operations. On the server side, “asynchronous mode” is even the only mode, because the execution environment is single-threaded, and if all HTTP requests are allowed to be executed synchronously, the server performance deteriorates dramatically and becomes unresponsive very quickly.

An asynchronous call does not prevent the code from being executed in sequence, but rather triggers the set logic at some point in the future, so we

  1. Don’t know when the logic will be called
  2. You can only define what the logic is when it’s triggered. Okay
  3. You have to wait while you work on the other logic
console.log('global begin')
setTimeout(function timer1() {
    console.log('timer1 invoke')},1800)
setTimeout(function timer2() {
    console.log('timer2 invoke')
    setTimeout(function inner() {
        console.log('inner invoke')},1000)},1000)
console.log('global end')

// global begin
// global end
// timer2 invoke
// timer1 invoke
// inner invoke
Copy the code

Analysis:

Firstly, the code structure is analyzed. This code is in asynchronous mode. When js reads the code, it first puts an anonymous function on the call stack.

Push the first line console.log(‘global begin’) onto the call stack and pop it up after execution. At this point, the console prints global BEGIN;

When the program goes to setTimeout, first push setTimeout(timer1) into the call stack, put the timer1 timer in the Web API thread, countdown to 1.8s, then push setTimeout(timer1) out of the call stack;

In the same step, push setTimeout(timer2) onto the call stack. The Web API thread puts the timer on timer2, counts down for 1 second, and then pushes setTimeout(timer2) off the call stack.

Then push console.log(‘global end’) onto the call stack and pop the call stack after execution. When the code is executed, anonymous is pop the call stack;

Web API puts Timer1 and Timer2 on the event queue, at which point Timer2 counts down first, enters the call stack, and executes the internal code. Push console.log(‘timer2 invoke’) onto the call stack and invoke it.

Then when you encounter setTimeout(inner), push it onto the call stack and add the inner timer to the Web API, counting down 1s. SetTimeout (inner) pops the call stack.

Log (‘timer1 Invoke ‘) on the call stack and then pop out.

The inner() timer then enters the task queue and, when the countdown is over, is pushed onto the call stack and pops up after execution. At this point, the program is finished.

3. Callback function

A callback function is a function that needs to be called asynchronously at an unspecified future point. In general, in this type of callback function, we often need to access external data frequently.

function foo(callback) {
    setTimeout(function () {
        callback()
    }, 3000)
}

foo(function () {
    console.log(This is a return function.)
    console.log('The caller defines the function, and the performer executes it.')
    console.log('Start is where the caller tells the performer what to do when the asynchronous task ends.')})Copy the code

4. Summary of Promise

Because the above callback functions can be nested, it is easy to cause the callback hell problem, that is, the following code is generated:

$.get('url1'.function (data1) {
    $.get('url2'.function (data2) {
        $.get('url3'.function (data3) {
            $.get('url4'.function (data4) {
                $.get('url5'.function (data5) {
                    $.get('url6'.function (data6) {
                        $.get('url7'.function (data7) {
                            // Slightly exaggerated, but true})})})})Copy the code

Hence the Promise, in the callback function, that promises what to do next after the asynchronous completion.

This is very depressing. There are three kinds of states: one is “start pending”, one is “fulfilled” and one is “failed”. Once the state of the promise is fulfilled, it cannot be changed. That is, when the state is fulfilled, the promise cannot be changed again, and vice versa.

There is a state of onFulfilled and onRejected.

  • What is thepromise?
  • promiseWhat is the meaning of birth and whypromise?
  • promiseWhat are the apis?
  • How do you use these apis? (MDN has a detailed usage, detailed can not be too detailed)
  • Ultimate solutionasync/awaitThe use of!
  • Write a promise by hand.