任务执行.md 2.1 KB

js中的任务类型

1. 宏任务
   1. settimeout
   2. setInterval
   3. MessageChannel
   4. I/O,事件队列
   5. setImmediate
   6. script
2. 微任务
   1. requestAnimationFrame
   2. MutationObserver
   3. Promise.[then/catch/finally]
   4. process.nexTick
   5. queueMicrotask

js中异步任务执行规则

  1. 先顺序执行下去,有遇到异步任务将其放置一边,然后继续执行下面的任务,执行完同步任务后再去看异步任务中的微任务是否有执行完了的,如果有则执行,执行完后则去执行宏任务,以此来完成一次循环

    js中async 和await的细节

    1. await

  2. 在js中 await 需要在async函数内进行执行, 遇到await时会等同于 promise 任务,将会在宏任务执行时立即执行,但是在await阻塞后的任务将会被当作是微任务去进行,

        async function fn(){
            await fn2();
            ...dostm
        }
        // 等同于
        function fn(){
            fn2().then(()=>{
                ...dostm
            })
        }
    

2. async

  1. 在js中的 async 相当于一个 promise 任务,

    js中promise和setTimeout谁先执行

  2. 在js中的promise视为微任务,settimeout为宏任务 根据执行规则微任务先执行,所以promise会先执行

  3. 示例代码

        console.log(1); //1
        new Promise((resolve, reject) => {
            console.log(2); //2
            resolve();
        }).then(() => {
            console.log(3) //4
        });
        setTimeout(() => {
            console.log(4) //6
        });
        setTimeout(() => {
            console.log(5) //7
        });
        new Promise((resolve, reject) => {
            console.log(6); //3
            resolve();
        }).then(() => {
            console.log(7); //5
        });
        new Promise((resolve, reject) => {
            console.log(8);
            setTimeout(() => {
                console.log(9)
                resolve();
            });
        }).then(() => {
            console.log(10);
        });
        // 1 2 6 8 3 7 4 5 9 10