Reputation: 17013
I'm fascinated by Node JS and have begun diving in, however, coming from a Java background, I am confused by examples like below where a chain of asynchronous calls are made that rely on a shared variable to keep track (so to determine when they have all completed to perform another action). I apologize if this question is overly basic, however I have been searching on this and haven't found an explanation, I am probably not using the right terms.
If you did something like this in Java, you would need to make the variable n synchronized to avoid collissions, otherwise its integrity could be compromised (this is just pseduo-code based off some more complex examples I read, sorry if its not perfect)
var n = 100
var funct_a = function(callback) {
return function() {
if (n == 0)
callback()
else
n--
}
}
for ( a in someArray) {
funct_a (function() {
//do something with variable a...
})
}
Is it that these are only running in one "thread", therefore they are not actually running on different CPU cores and cannot actually write to the variable at the same time? This seems the only logical explanation to me short of some core node server logic that resolves these types of conflicts. Any info to shed some light on this is appreciated.
Upvotes: 2
Views: 564
Reputation: 26199
In node.js all code works synchronously except I/O operations. It is totally different from Java. Try read this article it may help you to undersand.
Upvotes: 1
Reputation: 957
node.js is single-threaded but it sounds like you are more concerned about JavaScript's closures
and how function scope works in JavaScript. If you had some other code which had access to n
then in fact, yes, your callback()
invocation would not behave as you perhaps expected.
From a higher level perspective though, you should know that the CommonJS module will prevent your n
variable from being a global
, so unless you expose it or mess with it inside the module, n
will not be tampered with.
You probably already know about this, but I'd recommend touching up on the following:
HTH Mike
Upvotes: 2