I want function cb to be called only after function f1 and f2 have been finished (note that f1 and f2 are asynchronous and they might be called out of order at any time).
I'm trying to implement something like this, but it doesn't seem the best way to do this on node.js.
var l1 = false;
var l2 = false;
// function to be called after f1 and f2 have ended
function cb(err, res) {
if (err) {
console.log(err);
} else {
console.log('result = ' + res);
}
}
// f1 and f2 are practically identicals...
function f1(callback) {
console.log('f1 called');
l1 = true;
if (l2) {
console.log('f1 calling cb');
callback(null, 'one');
} else {
console.log('f2 wasn\'t called yet');
}
}
function f2(callback) {
console.log('f2 called');
l2 = true;
if (l1) {
console.log('f2 calling cb');
callback(null, 'two');
} else {
console.log('f1 wasn\'t called yet');
}
}
setTimeout(function() {
f1(cb); // will call cb
}, 3000);
setTimeout(function() {
f2(cb); // won't call cb
}, 1000);
// It will print:
// f2 called
// f1 wasn't called yet
// f1 called
// f1 calling cb
// result = one