前端开发核心知识进阶 —— 宏任务和微任务

前端开发核心知识进阶 —— 宏任务和微任务

首先看一段关于Promise的代码

console.log('start  here')

new Promise((resolve,reject) => {
    console.log('first promise constructor')
    resolve()
}).then(() => {
    console.log('first promise then')
    return new Promise((resolve,reject) => {
        console.log('second promise')
        resolve()
    }).then(() => {
        console.log('second promise then')
    })
}).then(() => {
    console.log('auther first promise then')
})

console.log('end here')

分析代码:

  1. 首先输出start then
  2. 接下来执行Promise构造函数,同步代码,输出first promise constructor同时将第一处Promisethen方法完成处理逻辑放入任务队列
  3. 继续执行同步代码,输出end here
  4. 同步代码全部执行完毕,然后执行任务队列的逻辑,输出first promise thensecond promise
  5. 当在then方法中返回一个Promise时,second promise thenthen方法进入任务队列,由于主线程中没有其他任务,因此会执行then方法,输出second promise then
  6. 最后输出auther first promise then

分类

任务队列中的异步任务其实又分为宏任务、微任务,也就是说宏任务和微任务虽然都是异步任务,都在任务队列,但是他们在不同的队列中。

宏任务:

  • setTimeout
  • setInterval
  • I/O
  • 事件
  • postMessage
  • setImmediate(Node.js中的特性,浏览器端已经废除该API)
  • requestAnimationFrame
  • UI渲染

微任务:

  • Promise.then
  • MutationObserver
  • process.nextTick(Node.js)

宏任务与微任务的优先级

console.log('start here')

const foo = () => (new Promise((resolve, reject) => {
    console.log('first promise constructor')
    
    let promise1 = new Promise((resolve,reject) => {
        console.log('second promise constructor')
        setTimeout(() => {
            console.log('setTimeout here')
            resolve()
        },0)
        resolve('promise1')
    })

    resolve('promise0')

    promise1.then(arg => console.log(arg))
}))

foo().then(arg => {
    console.log(arg)
})

console.log('end here')

宏任务队列:setTimeout

微任务队列:promise1.then,foo().then

输出结果:
“start here”
“first promise constructor”
“second promise constructor”
“end here”
“promise1”
“promise0”
“setTimeout here”

结论:
每次主线程执行栈为空的时候,引擎都会优先处理微任务队列,处理完后,再处理宏任务

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值