MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

node事件循环♻️ #55

Open MJingv opened 4 years ago

MJingv commented 4 years ago

node-event-loop

libuv 库怎么安排异步任务在主线程上执行


// test.js
setTimeout(() => console.log(1));
setImmediate(() => console.log(2));
process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));
(() => console.log(5))();

一、同步任务和异步任务

(() => console.log(5))();

二、本轮循环和次轮循环

异步任务可以分成两种

// 下面两行,次轮循环执行
setTimeout(() => console.log(1));
setImmediate(() => console.log(2));
// 下面两行,本轮循环执行
process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));

三、process.nextTick()

四、微任务

process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));
// 3
// 4

简单的顺序

1.同步任务
2.process.nextTick()
3.微任务       

五、事件循环的概念

"When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop."

六、事件循环的六个阶段

Node 定时器详解