The answer I came up with is as follows:
var count = 0; // Number of functions that need to run. This can be dynamically generated // In this case I call check(data, cb) a total of 3 times var functionNum = 3; function toCallAfter(){ console.log('I am a delayed function'); }
I had this for a validation function that ran once regularly and twice in a loop:
check(data, function(err){ // check is my asynchronous function to check data integrity if (err){ return cb(null, { // cb() is the return function for the containing function errCode: 'MISSINGINFO', statusCode: 403, message : 'All mandatory fields must be filled in' }); } // This part here is an implicit else count++; // Increment count each time required functions complete to // keep track of how many function have completed if (count === functionNum) { return anon(); } return; }); // Run twice more in a loop for(var i = 0; i < 2; i++) { check(data, function(err) { // calls check again in a loop if (err){ return cb(null, { errCode: 'MISSINGINFO', statusCode: 403, message : 'All mandatory fields must be filled in' }); } count++; if (count === functionNum) { return toCallAfter(); } return; }); }
Finally, I would like to point out a significant performance error of the alternative (and unusually general) answer:
(function wait() { if ( chatroom.json ) { chatroom.render(); } else { setTimeout( wait, 500 ); } })();
In this case, you essentially keep the browser or server (when using node.js) hostages for 500 milliseconds for each scan, which is an incredibly long time for the computer. It means a huge success. My solution to directly track the required completed functions does not contain time limits and will start immediately after all functions are completed.
source share