事件循环机制(even loop)

总结

  • 同步代码优先级高于异步代码优先级;
  • 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

posted @ 2019-07-02 15:01  璇璇璇璇璇  阅读(968)  评论(0编辑  收藏  举报