js事件机制,同步,异步,宏任务,微任务分析记录

写在前:js是单线程的(从上到下执行),同步任务进入主线程,异步任务进入队列。


宏任务:
    script(整体代码)
    setTimeout
    setInterval
    I/O
    UI交互事件
    postMessage
    MessageChannel
    setImmediate(Node.js 环境)
微任务:
    Promise.then (await后面的代码  等于  .then()里面的代码)
    Object.observe
    MutaionObserver
    process.nextTick(Node.js 环境)

看下面一段代码:分析输出结果(你可以先把填充的数字修改成空,重新填充以便更好的理解)

console.log('a');
async function async1() {
    console.log('2');
    await async2();
    console.log('8');
    new Promise(function(resolve) {
        console.log('9');
        resolve();
    }).then(function() {
        console.log('11');
    });
}
async function async2() {
    console.log('3');
    setTimeout(function() {
        console.log('13');
    }, 0)
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('7');
    });
}
 
console.log('1');
 
setTimeout(function() {
    console.log('12');
}, 0)
 
async1();
 
new Promise(function(resolve) {
    console.log('5');
    resolve();
}).then(function() {
    console.log('10');
});
console.log('6')

//a,1,2.......13

注意: 

new Promise(function(r) {
    console.log('1');
    r();
})
async function aa() {
    console.log('2');
    await cc();
    console.log('3');
}

注意:在.then() 之前的代码为同步
      await cc() 为同步

规则:同步进入主线程,异步进入队列,异步中微任务优先于宏任务


注:微任务中.nextTick 优先于.then()执行
注:异步中微任务优先,.then() 优先于 setTimeout

最后:如果有便捷的理解过程可以留言,此文若有问题请留言以便修正 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值