-
Notifications
You must be signed in to change notification settings - Fork 64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Chapter 1: event loop with different result #3
Comments
Thanks for submitting this. I've reproduced the error. I'll try to find the issue and submit it to the publisher. |
Hello, I've started reading this book and stumbled upon the same behavior. After studying how callbacks, promises, async/await, and the Node.js event loop works, it turns out that this output, i.e., 2 1 4... or 2 4 1... is normal. Actually, both snippets are equivalent and exhibit the same behavior which can be observed if executed multiple enough times. So, why is this happening? In Event Loop Explained it states the following:
So, when we execute these code snippets in a standalone script, the event loop is only initialized and not running yet. The loop will start only after the execution of the full script which happens outside of an I/O cycle. Now, if a script is outside of an I/O cycle the To have a deterministic order of execution we have to make these calls in an I/O cycle. For example, the two code snippets could be written like this:
In both cases the output is ensured to be the following: 2 1 4 3 6 8 5 7 The confusion is most probably caused by the book's statement that the poll phase is the first phase of the event loop and that the script execution is happening during this phase, which is actually a good model of thinking when there are I/O operations involved, although to be strict the first phase is the
Note that
And based on all the above analysis, if these calls are made inside an I/O cycle the
and as expected the output is:
|
page number: 13
node: v14.17.3
macOs Big Sur: Version 11.6
log out:
2 4 1 3 6 8 5 7
log out:
2 1 4 3 6 8 5 7
The text was updated successfully, but these errors were encountered: