事件循环机制(even loop)

本文深入探讨了Node.js中事件循环的工作原理,包括同步与异步代码执行的优先级、微任务与宏任务的区别,以及不同事件回调的执行顺序。通过具体代码示例,详细解释了process.nextTick、Promise.then、setTimeout、setInterval和setImmediate等函数的执行时机和优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结

  • 同步代码优先级高于异步代码优先级;
  • new Promise(fn)中的fn是同步执行;
  • 微任务优先级高于宏任务优先级;
    • 微任务:process.nextTick() > Promise.then()
    • 宏任务:setTimeout、setInterval > setImmediate

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})
// 输出结果:1  7  6  8  2  4  9  11  3  10  5  12
setImmediate(() => {
    console.log('第一行setImmediate');
}, 0);
var time = setInterval(() => {
    console.log('第二行 setInterval');
    clearInterval(time);
}, 0);
setTimeout(() => {
    console.log('第三行 setTimeout');
}, 0);
var time1 = setInterval(() => {
    console.log('第四行 setInterval');
    clearInterval(time1);
}, 0);
setImmediate(() => {
    console.log('第五行setImmediate');
}, 0);
process.nextTick(() => {
    console.log('第六行 nextTick');
});
new Promise((resolve, reject) => {
    reject('reject');
    console.log('第七行Promise');
    resolve('resolve');
}).then(() => {
    console.log('第八行 Promise then resolve');
}.catch() => {
    console.log('第八行 Promise then reject');
});

// 输出结果:
// 第七行Promise【先执行同步】
// 第六行 nextTick【微任务】
// 第八行 Promise then resolve【微任务】
// 第二行 setInterval【宏任务】
// 第三行 setTimeout【宏任务】
// 第四行 setInterval【宏任务】
// 第一行setImmediate【宏任务】
// 第五行setImmediate【宏任务】

请注意,node环境下的事件监听依赖libuv与前端环境不完全相同,输出顺序可能会有误差!!

请注意:chrome中间层 & node中间层libuv

转载于:https://www.cnblogs.com/hujingxuan1437/p/11120708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值