javascript

js的执行机制

    console.log('1');

    async function async1() {
        console.log('2');
        await async2();
        console.log('3');
    }
    async function async2() {
        console.log('4');
    }

    setTimeout(function () {
        console.log('5');
        new Promise(function (resolve) {
            console.log('6');
            resolve();
        }).then(function () {
            console.log('7')
        })
    })

    async1();
    new Promise(function (resolve) {
        console.log('8');
        resolve();
    }).then(function () {
        console.log('9');
    });

    console.log('10');

这串代码的执行机制是怎么样的

  1. 全局js代码执行,console.log('1');输出1
  2. 创建async1,async2函数,但不执行;
  3. setTimeout 宏任务队列
  4. async1执行;console.log('2');输出2
  5. await async2();console.log('4');输出4
  6. console.log('3');放入微任务队列;
  7. 执行new Promise ,console.log('8');输出:8
  8. then 放入微任务队列;
  9. console.log('10');执行10
  10. 执行微任务队列:console.log('3');输出3
  11. 执行.then(function () { console.log('9') });输出9
  12. 全局宏任务和微任务执行完成;
  13. 执行宏任务队列setTimeout,console.log('5');输出5
  14. 执行settimeout 中的new Promise,console.log('6');输出6
  15. then放入微任务中;
  16. 宏任务执行完成,开始执行微任务队列;
  17. then console.log('7')输出7
    最后全部顺序:1,2,4,8,10,3,9,5,6,7
    不理解可以看看https://blog.csdn.net/GTbond/article/details/121980240