宏任务和微任务的简述

1,318 阅读1分钟

宏任务:
setTimeout
setInterval
setImmediate
requestAnimationFrame

微任务:
process.nextTick
MutationObserver
Promise (.then .catch .finally)

执行顺序

宏任务代表:setTimeout
微任务代表:Promise

const func = () => {
    console.log(0);
    setTimeout(()=>{
        console.log(1);
    },10);
    setTimeout(()=>{
        console.log(2);
    })
    new Promise((res)=>{
        console.log(3)
        return res();
    }).then(()=>{
        console.log(4);
    });
    setTimeout(()=>{
        console.log(5);
        new Promise((res)=>{
            console.log(6)
            return res();
        }).then((res)=>{
            console.log(7);
        });
        console.log(8)
    });
    console.log(9);
}

func();  // 第一轮: 0 3 9   4   第二轮:  2 5 6 8   7  1

结论: 先由script从上到下执行,遇到微任务也一起执行,遇到宏任务则放在事件队列里面后执行;宏任务也是由script从上至下执行,遇到微任务也会一起执行。
注意:

  1. setTimeout和Promise都属于异步执行。
  2. Promise首个函数为微任务里面的执行函数,.then()里面的函数属于异步函数。

setTimeout

setTimeout是Windows的方法。
第一个参数为需要执行的代码,第二个参数为多少毫秒后执行第一个参数。

setTimeout(要执行的代码, 等待的毫秒数)

举个栗子

const func = () => {
    console.log('请等待三秒');
    setTimeout(()=>{
        console.log('三秒已到')
    },3000)
}
func();

Promise

Promise的三个状态:

  1. 初始状态(pending)
  2. 操作成功(fulfilled)
  3. 操作失败(rejected)

.then的操作接收的第一个值为上一次.then的返回值。
如果.then的操作没有函数意义则接收上一次的值。
举个栗子

const func = () =>{
    new Promise((res)=>{
        // 返回1
        return res(1)
    }).then(
        // 只是个路过打酱油的
        console.log(2)
    ).then((res)=>{
        // 输出上一次的结果,不再返回值
        console.log(res)
    }).then((res)=>{
        // 没有接收到上一次的结果
        console.log(res);
    });
}
func();   // 2 1 undefined

本文章以学习为主,欢迎大家指出不当之处,左边点赞支持,请大家踊跃留言,积极探讨。