J
J
JackShcherbakov2019-03-26 19:32:55
Node.js
JackShcherbakov, 2019-03-26 19:32:55

SetImmediate fires before the callback. Why?

Hello!
There is a code:

var fs = require('fs');

fs.open(__filename, "r", function(err, file){
  console.log("IO!");
});

setImmediate(function(){
  console.log("immidiate");
});

process.nextTick(function(){
  console.log("nextTick!");
});

Result:
nextTick!
immidiate
IO!

Although in the screencast https://learn.javascript.ru/screencast/nodejs#node... the exact same code gives the following output:
nextTick!
IO!
immidiate

Why?
Thanks in advance to everyone who helps!
UPD:
The documentation says:
Schedules the "immediate" execution of the callback after I/O events' callbacks.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2019-03-26
@bingo347

process.nextTick - executed in the next microtask (in this case, it will be at the current iteration of the event-loop, immediately after all synchronous actions)
setImmediate - immediately throws the function at the end of the event-loop
queue fs.open - first waits for the IO operation to complete, and only then will be in the event-loop queue
theoretically IO operation can complete before setImmediate is called, then the fs.open callback will be called earlier, since it got into the queue earlier
, but most often it will still be setImmediate earlier

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question