xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js process.nextTick All In One

Node.js process.nextTick All In One

The Node.js Event Loop, Timers, and process.nextTick()

image

// process.nextTick

https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

https://nodejs.org/zh-cn/docs/guides/event-loop-timers-and-nexttick/

process.nextTick vs setImmediate

const baz = () => console.log('baz');
const foo = () => console.log('foo');
const zoo = () => console.log('zoo');

const start = () => {
  console.log('start');
  setImmediate(baz);
  new Promise((resolve, reject) => {
    resolve('bar');
  }).then((resolve) => {
    console.log(resolve);
    process.nextTick(zoo);
  });
  process.nextTick(foo);
};

start();

// start foo bar zoo baz

https://nodejs.dev/en/learn/understanding-setimmediate/

https://nodejs.dev/zh-cn/learn/understanding-processnexttick/

import { nextTick } from 'node:process';

console.log('start');
nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback

https://nodejs.org/api/process.html#processnexttickcallback-args

queueMicrotask() vs. process.nextTick()

import { nextTick } from 'node:process';

Promise.resolve().then(() => console.log(2));
queueMicrotask(() => console.log(3));
nextTick(() => console.log(1));
// Output:
// 1
// 2
// 3
console.log('start');
queueMicrotask(() => {
  console.log('microtask callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// microtask callback

https://nodejs.org/api/process.html#when-to-use-queuemicrotask-vs-processnexttick

queueMicrotask

let id = setInterval(() => {
  console.log(`4`);
  clearInterval(id);
});

setTimeout(() => {
  console.log(`3`);
});

queueMicrotask(() => {
  console.log(`2`);
});

console.log(`1`);

/*

1
2

3
4

*/

image

let id = setInterval(() => {
  console.log(`5`);
  clearInterval(id);
});

setTimeout(() => {
  console.log(`4`);
});

Promise.resolve().then(() => console.log(`2`));

queueMicrotask(() => {
  console.log(`3`);
});

console.log(`1`);

/*

1
2

3
4
5

*/

image

https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

process.nextTick

https://medium.com/@amanhimself/how-process-nexttick-works-in-node-js-cb327812e083

https://timnew.me/blog/2014/06/23/process-nexttick-implementation-in-browser/

https://www.geeksforgeeks.org/difference-between-process-nexttick-and-setimmediate-methods/

https://stackoverflow.com/questions/40629456/why-and-when-to-use-process-nexttick



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-02-28 22:53  xgqfrms  阅读(28)  评论(1编辑  收藏  举报