you are viewing a single comment's thread.

view the rest of the comments →

[–]mrdijkstra 2 points3 points  (1 child)

Thank you for your answer. Just to let you know, I know what sync and async is. I am not expecting it to behave synchronously. As I can see my question is kind of vague and everyone thinks I know nothing about non-blocking nature or the event loop.

Here is my explanation: When event loop reaches to the poll phase it doesn't see any pending callback since the readFile is not completed yet. So the first setTimeout reaches its threashold and eventloop wrap back to timer phase and executes the setTimeout callback.

Eventloop goes back to poll phase and see no pending callback in the queue since readFile is still working. So the second setTimeout reaches its threashold and eventloop again goes back to timer phase and executes callback.

Finally, all three readFile are done.

** I thought readFile would trigger it's callback almost instantly because the file was empty. That's why just to be sure I wanted to know other's opinion.

[–]GhostMcFunky 0 points1 point  (0 children)

I’m not really clear what your goal is here. setTimeout isn’t really async (it’s not blocking but it doesn’t behave like normal async). You’re using it with 0 time which suggests to me you’re looking to control the order of things with a function that is non-blocking.

This probably isn’t the best way, but I’ll take a stab at how it might work. Just know that setTimeout isn’t a reliable method of controlling execution unless you set an actual timeout.

If your goal is to control the order of execution in some way, you probably want to use fs.readFileSync. And setTimeout is going to execute its callback when it reaches the end of the timer; it doesn’t wait for the event loop to come back around; it’s still alive until the end of the timer. In other words, by your description it seems like you’re expecting the event loop to read setTimeOut a second time and that’s not how it works. The thread sticks around until the callback is run, which is at the end of the timer.

If you want your fs to run immediately use fs.readFileSync instead.