nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.44k stars 276 forks source link

setImmediate() ,process.nextTick() understanding #4366

Closed maccrin closed 2 weeks ago

maccrin commented 3 months ago

Enter your suggestions in details:

when I run the below code in ES module

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

start();

output

start
bar
foo
zoo
baz

As per the documentation https://github.com/nodejs/nodejs.org/blob/main/pages/en/learn/asynchronous-work/understanding-setimmediate.md It should be

start
foo
bar
zoo
baz

I got the expected output as per documentation when run under CommonJS module. so is the output is dependent on ES/CommonJS, it would be helpful if that is mentioned in the documentation.

thisalihassan commented 3 months ago

@maccrin actually same I am on ubuntu node v20.11.1 if I paste the code in test.js and run node test.js my output is similar "bar" comes before foo sometimes. however this is not always the case you can try again it will be different "foo" will come before "bar". so I am not sure what could be the reason here. If someone explains this weird behavior that would be great.

but when I run the code in the node shell it gives the expected out like in the article

I also tested in mac in both ways the expected output (from the article) was similar in both cases

Trott commented 3 months ago

@nodejs/timers

RedYetiDev commented 2 weeks ago

(re)pinging @nodejs/timers

benjamingr commented 2 weeks ago

This was already fixed in the docs:

The principle aforementioned holds true in CommonJS cases, but keep in mind in ES Modules, e.g. mjs files, the execution order will be different:

maccrin commented 2 weeks ago

This was already fixed in the docs:

The principle aforementioned holds true in CommonJS cases, but keep in mind in ES Modules, e.g. mjs files, the execution order will be different:

Thanks for the update.