I was coding some Node.js and I thought, coming from a Java background, that I should figure out how to create my own "wait" functionality. Obviously, it will be a little different since Java is designed to be multi-threaded and Node is not. Anyway, the desired functionality I want in Node is that I want to create a blocking function myself - such that if some boolean in the program is not set, I might want to call process.nextTick()
until the boolean gets set.
So it would be:
var bool = false;
function foo(){
var b = baz();
}
function baz(){
while(!bool){
process.nextTick(function() {
return baz(arguments);
});
}
return {};
}
function setBool(number) {
setTimeout(function () {
bool = false;
}, number);
}
process.nextTick(wait);
setBool(3000);
so this question is twofold:
(1) is this the best way to implement a waiting type functionality in Node.js?
(2) If I called baz(arguments) instead the baz function (recursively) what happens in terms of the execution? Generally, when you want the return value from function X, but function X calls itself a few times before returning, does this pose any problems? Is it no big deal and it turns out to be the same return value? I have thought about this before but never really worried about it or investigated it.
Do not 'wait' in Node.js. "Waiting" blocks ALL other execution. That's an important note because if you block, then the boolean can NEVER set changed. JavaScript, and especially in Node, uses an event driven model. Do this, when that.
So the best way? It's opinion based but this is one way:
var bool = false;
function foo() {
console.log('Listening for true');
baz(function() {
//Do something when called
console.log('It\'s finally true!');
});
}
function baz(callback) {
setImmediate(function() {
if (bool)
callback();
else
baz(callback);
});
}
foo();
setTimeout(function() {
console.log('Setting to true');
bool = true;
}, 4000);