事件循环机制(even loop)

2020-11-06  本文已影响0人  璇璇璇璇璇1437

总结

事件线程
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中间层 vs node中间层libuv

在node环境下,process.nextTick的优先级高于Promise,也就是说:在宏任务结束后会先执行微任务队列中的nextTickQueue,然后才会执行微任务中的Promise。

上一篇下一篇

猜你喜欢

热点阅读