Don't use flags! They are completely unnecessary.
Also don't do anything special in A()
or B()
. Just write them as you would normally to perform their duties.
Just implement a queue in the form of a dynamically updated promise chain.
var q_ = Promise.resolve();
function queue(fn) {
q_ = q_.then(fn);
return q_;
}
Now you can queue A
and B
, or any other function, as follows :
queue(A);
queue(B);
queue(someOtherFunction);
Or, if you need to pass parameters :
queue(A.bind(null, 'a', 'b', 'c'));
queue(B.bind(null, 'x', 'y', 'z'));
queue(someOtherFunction.bind(null, 1, 2, 3));
As a bonus,
A()
and B()
(and other functions) remain available to be called directly (unqueued).
- you needn't worry whether functions passed to
queue()
are synchronous or asynchronous. It will work with either.
DEMO