Here is an example of how to do this very simply with promises:
var p = Promise.resolve(); // assuming Bluebird promises or Node 0.11.13+ with Promises.
// create a new empty resolved promise.
function doFirst(act){
return p = p.then(function(){
return someFirstAction(act); // assumes someFirstAction returns a promise
})
}
function doSecond(act){
return p p.then(function(){
return someSecondAction(act); // assumes someFirstAction returns a promise
})
}
What this does is queue the operations on the single chain. When it resolves the chain resolves. It also returns the returned promise, so you can unwrap it and get the value.
For example:
doFirst(1);
doSecond(2);
// some point in the future
doFirst(3).then(function(value){
// both doFirst(1) and doSecond(2) are done here
// the value argument is the resolution value of doFirst(3)
});
If you're unsure on how to convert your API to promises - see this question.
Since, you also want to limit the number of times a particular action is run, you can create special methods for it:
doFirst.queued = false;
function doFirst(act){
if(doFirst.queued) return; // already queued
doFirst.queued = true;
return p = p.then(function(){
return someFirstAction(act).finally(function(){
doFirst.queued = false;
});
})
}
doSecond.queued = false;
function doSecond(act){
if(doSecond.queued) return; // already queued
doSecond.queued = true;
return p = p.then(function(){
return someSecondAction(act); // assumes someFirstAction returns a promise
}).finally(function(){
doSecond.queued = false;
});
}