nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
104.27k stars 28.06k forks source link

The order of code execution is wrong #52792

Closed Regnised closed 2 weeks ago

Regnised commented 2 weeks ago

Affected URL(s)

https://github.com/nodejs/nodejs.org/edit/main/pages/en/learn/asynchronous-work/understanding-setimmediate.md

Description of the problem

I've tried to execute the code from the page several times on Node.js 18 and 20 but have got the save result

start
bar
foo
zoo
baz

Why it is not the same as in documentation?

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
climba03003 commented 2 weeks ago

The document is run in CommonJS and your result seems like run in ESM.

Regnised commented 2 weeks ago

Yep, you are right.