001--Node.js之EventLoop

The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.

详情见下图

我们都知道JS是单线程的,当一个任务进入Node.js解释器的执行栈后,会首先看是同步还是异步代码,同步会推入主线程进行解释,异步代码会推入eventLoop事件循环中,这些任务会分为宏任务或者微任务,当执行栈中没有同步代码时,会先执行宏任务:主体script,setTimeout,setInterval,后执行微任务Promise.then,process.nextTick

console.log('script start');

setTimeout(function() {
  console.log('setTimeout');
}, 0);

Promise.resolve().then(function() {
  console.log('promise1');
}).then(function() {
  console.log('promise2');
});

console.log('script end');
//script start
//script end
//promise1
//promise2
//setTimeout
setTimeout(() => {

    // 宏任务
    new Promise(resolve => {
        console.log('promise')
        resolve();
    }).then(() => {
        //微任务
        console.log('then')
    });

    // 宏任务
    console.log('宏任务',1);
    // 宏任务
    setTimeout(() => {

        console.log('setTimeout',1)

    }, 1000);

}, 1000);
2
// promise
//宏任务 1
//then
//setTimeout 1
console.log('script start');

setTimeout(function() {
    
    new Promise((resolve)=>{}).then()

    setTimeout(function() {
    
    }, 0);

}, 0);

new Promise(resolve => {
    console.log('promise start');
    setTimeout(() => {
        console.log('setTimeout2');
        resolve();
    }, 1000)
}).then(function() {
  console.log('promise1');
}).then(function() {
  console.log('promise2');
});

console.log('script end');
//script start
// promise start
// script end
// setTimeout2
// promise1
// promise2

 2019-05-10  17:11:45

猜你喜欢

转载自www.cnblogs.com/ccbest/p/10845536.html