Node.js 的eventLoop

1、timers阶段(setTimeout)
2、I/O callbacks阶段
3、idle prepare 阶段
4、poll 轮询阶段,停留时间最长,可以随时离开。

a. 主要用来处理 I/O 事件,该阶段中 Node 会不停询问操作系统有没有文件数
据、网络数据等
b. 如果 Node 发现有 timer 快到时间了或者有 setImmediate 任务,就会主动离
开 poll 阶段

5、check阶段,主要处理setimmediate任务
6、close callback阶段
node.js会不停的从1~6循环处理各种事件,这个过程叫事件循环

node js 要处理很多事件包括IO事件 文件事件 网络事件 事件分类分为6类
按照这6类不停的去循环 这个过程就叫做事件循环

nextTick

process.nextTick(fn) 的 fn 会在什么时候执行?

在 Node.js 11 之前,会在每个阶段的末尾集中执行(俗称队尾执行)。
在 Node.js 11 之后,会在每个阶段的任务间隙执行(俗称插队执行)。

ps: 浏览器上跟node.js11之后的情况类似

setTimeout(()=>console.log(1))
setTimeout(()=>{
  console.log(2)
  process.nextTick(()=>{
    console.log('nextTick');
  })
})
setTimeout(()=>console.log(3))
setTimeout(()=>console.log(4))


//Node.js 11 之前 1 2 3 4 nextTick
//Node.js 11 之后 1 2 nextTick 3 4 

Promise

Promise.resolve().then(fn) fn会在什么时候执行

一般直接参考process.nextTick(fn)实现。

async / await

参考Promise即可。

async function async1() {
  console.log('1') // 2
  // await async2()
  //  console.log('2')

  // 改下如下
  async2().then(() => {
    console.log('2')
  })
}
async function async2() {
  console.log('3') // 3
}

console.log('4') // 1
setTimeout(function () {
  console.log('5')
}, 0)

async1();

new Promise(function (resolve) {
  console.log('6') // 4 立即执行
  resolve();
}).then(function () {
  console.log('7')
})
console.log('8') // 5

  /**
   * timer = [5]
   * next = [2, 7]
   * 
   * 2 7 5
   */


//4 1 3 6 8 2 7 5

你可能感兴趣的:(Node.js 的eventLoop)