两道NodeJS事件循环的面试题

115 阅读1分钟
async function async1 () {
    console.log( 'async1 start' );
    await async2(); // await 后边的函数会同步的执行 
    // 之后的部分会被放入到 微任务队列中进行等待
    console.log( 'async1 end' );
}

async function async2 () {
    console.log( 'async2' );
}

console.log( 'script start' );


setTimeout( () => {
    console.log( 'setTimeout0' );
}, 0 );

setTimeout( () => {
    console.log( 'setTimeout300' );
}, 300 );

setImmediate( () => console.log( 'setImmediate' ) );

process.nextTick( () => console.log( 'nextTick1' ) );

async1();

process.nextTick( () => console.log( 'nextTick2' ) );

new Promise( ( resolve ) => {
    console.log( 'promise1' );
    resolve( 0 );
    console.log( 'promise2' );
} ).then( () => {
    console.log( 'promise3' );
} );

console.log( 'script end' );

// 一次tick顺序为
// main script -> nextTicks -> microtask -> timers -> io -> immediate 
// node 的事件循环中 会将每个队列都清空之后 在执行之后的队列

// script start
// async1 start;
// async2;
// promise1;
// promise2
// script end;
// nextTick1;
// nextTick2
// async1 end;
// promise3;
// setTimeout0;
// setImmediate;
// setTimeout300;



setTimeout( () => {
    console.log( 'setTimeout' );
} );

setImmediate( () => {
    console.log( 'setImmediate' );
} );

// 结果为  setTimeout setImmediate 或者是 setImmediate setTimeout
// 因为 setTimeout函数执行的时间和初始化事件循环的时间未知 导致两种不同的结果
// 在poll阶段 时间循环 等待的时间最长 可能产生阻塞,阻塞的目的是让当有异步io被处理时,尽可能快的让代码执行