I wrote this queue
object to handle async functions in JavaScript.
I'm not sure if this is a correct approach.
Is this steady enough to run on nodeJS or it may fail/fault?
var queue = {
callbacks: [],
start: function(){
this.returnVal = this.callbacks.shift()();
},
next: function(returnVal){
try{
queue.returnVal = queue.callbacks.shift()( returnVal );
} catch(e) { console.error("oops, this function failed..:", e)}
},
add: function( newCallback ){ // adds new funcion to the end of the queue
this.callbacks.push(newCallback);
}
}
/* generic functions */
function f1(param1){
console.log('running f1');
console.log('param1 is:', param1);
queue.next('this string was returned from f1'); // return
}
function f2(param1){
console.log('running f2');
console.log('param1 is:', param1);
setTimeout(function(){ // simulate async
console.log('adding f9 function to the queue');
queue.add(f9);
queue.next('this string was returned from f2 after adding f9 to the queue'); // f2 return
}, 1000);
}
function f3(param1){
console.log('running f3');
console.log('param1 is:', param1);
queue.next(); // f3 return
}
function f9(){
console.log('running f9');
queue.next('f9 returns');
}
queue.callbacks.push(f1, f2, f3);
queue.start();
the output is:
running f1
param1 is: undefined
running f2
param1 is: this string was returned from f1
adding f9 function to the queue
running f3
param1 is: this string was returned from f2 after adding f9 to the queue
running f9
oops, this function failed..: [TypeError: queue.callbacks.pop(...) is not a function]
Note that the last line error is due to queue
is now empty.
Can the try catch
there save nodeJS from crashing?