js synchronous and asynchronous

1. js execution mechanism

A major feature of the JavaScript language is single-threaded , that is (only one thing can be done at the same time). Because JavaScript was born to handle user interaction on the page and manipulate the DOM. For example, add and delete operations on a DOM element. It cannot be done at the same time, it should be added first, and then deleted.

Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed. The problem caused by this is: if the execution time of JS is too long, the rendering of the page will be incoherent, resulting in the feeling of page rendering and loading blocking. Therefore, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, so synchronous and asynchronous appear in js .

Two, synchronous and asynchronous

Synchronous task: Execute the next task after the previous task is completed, and the execution order of the program is consistent with the arrangement order of the tasks.

Asynchronous tasks: multi-tasking and multi-threading, for example: while doing one thing, you can do other things.

explain:

Synchronous tasks are executed on the main thread, forming an execution stack.

Asynchronous tasks (the asynchrony of js is implemented through the callback function and put into the message queue) such as:

① Ordinary events. click, resize, etc.
② data loading, load, error, etc.
③ timer, setInterval, setTimeout, etc.

3. Execution sequence

① Execute the synchronous tasks in the execution stack first
② Put the asynchronous tasks (callback functions) into the task queue
③ Once all the synchronous tasks in the execution stack are executed, the system will read the asynchronous tasks in the task queue in order The fetched asynchronous task ends the waiting state, enters the execution stack, and starts executing.

 As shown in the picture:

 4. Event loop

 We divide tasks into synchronous tasks and asynchronous tasks . js divides asynchronous tasks into macro tasks and micro tasks

After es5, JavaScript introduced promises, so that the JavaScript engine itself can initiate asynchronous tasks without the need for a browser.

Macro tasks are initiated by browsers and nodes, and
micro tasks are initiated by js engines, such as promises (Promise itself is synchronous, and the callback function of then/catch is asynchronous)

So we may divide the code into 3 types

① Synchronous code (js execution stack/callback stack)
② Asynchronous code of microtasks (js engine)
   process.nextTick (node)
   promise.then( ) catch( ) Promise itself is synchronous, and the callback function of then/catch is asynchronous microtask Task Async/Await     Object.observer, etc. ③ Macro task asynchronous code    script (code block)    setTimeout/ setInterval timer    setImmediate timer Look at the execution order of the three codes: synchronous code→→→→ microtask asynchronous code (promise etc.) →→→→Asynchronous code for macro tasks (setTimeout/setInterval etc.)             
 
 






As shown in the picture:

Five, the case

5-1 case:

<script>
    console.log(1);
    setTimeout(function() {
        console.log(2);
    },0)

    const p = new Promise((res,rej)=> {
        console.log(3);
        res(1000)
        console.log(4);
    }).then(data=> {
        console.log(data);
    })
    console.log(5);  //结果为 1 3 4 5 1000 2 
</script>

analyze:

 5-2 case:

<script>
   new Promise((resolve,reject)=> {
        resolve(1)
        new Promise((resolve,reject)=> {
            resolve(2)
        }).then(data => {
            console.log(data);
        })
    }).then(data=> {
        console.log(data);
    })
    console.log(3);
    // 3 2 1
</script>

 5-3 case:

<script>
   setTimeout(() => {
        console.log(1);
    }, 0)
    new Promise((resolve, reject) => {
        console.log(2);
        resolve('p1')
        new Promise((resolve, reject) => {
            console.log(3);
            setTimeout(() => {
                resolve('setTimeout2')
                console.log(4);
            }, 0)
            resolve('p2')
        }).then(data => {
            console.log(data);
        })

        setTimeout(() => {
            resolve('setTimeout1')
            console.log(5);
        }, 0)
    }).then(data1 => {
        console.log(data1);
    })
    console.log(6);
  // 2 3 6 p2 p1 1 4 5
</script>

 analyze:

  ​​​​5-4 case:

<script>
   async function async1() {
        console.log('async1 start');
        await async2();
        console.log('async1 end');
    }
    async function async2() {
        console.log('async2');
    }
    console.log('script start');
    setTimeout(()=> {
        console.log('setTimeout');
    },0)
    async1();
</script>

analyze:

   ​​​​5-5 cases:

<script>
    setTimeout(() => {
        console.log(0);
    }, 0)
    new Promise((res, rej) => {
        console.log(1);
        res();
    }).then(() => {
        console.log(2);
        new Promise((res, rej) => {
            console.log(3);
            res();
        }).then(() => {
            console.log(4);
        }).then(() => {
            console.log(5);
        })
    }).then(() => {
        console.log(6);
    })
    new Promise((resolve, reject) => {
        console.log(7);
        resolve(8);
    }).then((data) => {
        console.log(data);
        console.log(9);
    })
    //结果为???
</script>

Guess you like

Origin blog.csdn.net/Tianxiaoxixi/article/details/130204194
Recommended