Created
April 7, 2015 11:51
-
-
Save joepie91/98576de0fab7badec167 to your computer and use it in GitHub Desktop.
Predictable sync vs. async in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var i = 0; | |
maybeSyncMaybeAsync(function(){ | |
i++; | |
}); | |
console.log("The value of i is", i); |
@AdamPflug Right. The point was to demonstrate how an unpredictable API can cause issues, with an example that's as simple as possible to follow - whether this example can be changed isn't relevant, it's intentionally kept simple.
"Changing the order of statements" is not always possible, and sometimes simply incorrect. That's why it's so important to have a predictable API.
to make this into a runnable example - async and sync versions of the function could be added -
//First try this
//This is asynchronous execution of the callback
function maybeSyncMaybeAsync(cb) {
process.nextTick(cb);
}
/*
//Then try this definition
//This is synchronous
function maybeSyncMaybeAsync(cb) {
cb();
}
*/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively this could just be rewritten so it doesn't matter :)
In threaded languages because of write-locks it gets trickier (or impossible), but in JS you can usually avoid the issue by changing the order of statements so you don't depend on the callback being called synchronously or asynchronously.