In my code I have three variables whose value depend on an external function call, they can be set to true in any moment and in any order, so, they are more like flags.
I need a function to be only once these three variables are set to true.
How can I perform a wait for these three variables to be true, without blocking my server, in an asynchronous way?
(I do not want to be refered to external libraries)
I generally like to use the async library for doing things like this, but since you don't want to be referred to external libraries for this. I will write a simple function that checks it at an interval to see if the variables have been set.
Interval Check Method
var _flagCheck = setInterval(function() {
if (flag1 === true && flag2 === true && flag3 === true) {
clearInterval(_flagCheck);
theCallback(); // the function to run once all flags are true
}
}, 100); // interval set at 100 milliseconds
Async Library Parallel Method
var async = require('async');
async.parallel([
function(callback) {
// handle flag 1 processing
callback(null);
},
function(callback) {
// handle flag 2 processing
callback(null);
},
function(callback) {
// handle flag 3 processing
callback(null);
},
], function(err) {
// all tasks have completed, run any post-processing.
});
If you control state of these variables - why not trigger some event when you set this variables? Even better - have some object that incapsulates this logic. Something like:
function StateChecker(callback) {
var obj = this;
['a', 'b', 'c'].forEach(function (variable) {
Object.defineProperty(obj, variable, {
get: function () { return a; }
set: function (v) { values[variable] = v; check(); }
});
});
function check() {
if (a && b && c) callback();
}
}
var checker = new StateChecker(function () {
console.log('all true');
});
checker.a = true;
checker.b = true;
checker.c = true;
> 'all true'