1

This is my first code:

const express = require('express');
const app = express();

app.get('', (req, res) => {
  setTimeout(() => console.log('timeout'));

  setImmediate(() => console.log('immediate'));

  Promise.resolve().then(() => console.log('promise'));

  process.nextTick(() => console.log('nextTick'));
})

app.listen(3000);

When i call localhost:3000, it prints:

nextTick -> promise -> immediate -> timeout

However with second code:

setTimeout(() => console.log('timeout'));

setImmediate(() => console.log('immediate'));

Promise.resolve().then(() => console.log('promise'));

process.nextTick(() => console.log('nextTick'));

when i run it prints different:

nextTick -> promise -> timeout -> immediate

Why I have 2 different results. Thank for your attention.

1 Answers1

1

In the first code, When a request is made to the server, the callback function you provided is executed. Within that callback function, you're using several asynchronous functions: setTimeout, setImmediate, Promise.resolve().then(), and process.nextTick.

The order in which these asynchronous functions are executed depends on the timing of the event loop. In this case, the order is nextTick -> promise -> immediate -> timeout. This is because process.nextTick has the highest priority and is executed before any other async function, followed by Promise.resolve().then(), setImmediate, and setTimeout.

In the second code, you're running the code as a standalone script. The order of the async functions is still determined by the event loop, but the timing is slightly different. In this case, the order is nextTick -> promise -> timeout -> immediate. This is because setTimeout has a minimum delay of 1ms, so it's scheduled to execute after the other async functions.

So the order of execution of asynchronous functions is determined by the event loop and can vary depending on the timing and structure of your code.

mw509
  • 1,957
  • 1
  • 19
  • 25