Assuming that the commands you want to perform are some sort of async function call:
var Q = require('q');
// This is the function you want to perform. For example purposes, all this
// does is use `setTimeout` to fake an async operation that takes some time.
function asyncOperation(input, cb) {
setTimeout(function() {
cb();
}, 250);
};
function performCommand(command) {
console.log('performing command', command);
// Here the async function is called with an argument (`command`),
// and once it's done, an extra delay is added (this could be optional
// depending on the command that is executed).
return Q.nfcall(asyncOperation, command).delay(1000);
}
// Set up a sequential promise chain, where a command is executed
// only when the previous has finished.
var chain = Q();
[ 'cmd1', 'cmd2', 'cmd3' ].forEach(function(step) {
chain = chain.then(performCommand.bind(null, step));
});
// At this point, all commands have been executed.
chain.then(function() {
console.log('all done!');
});
I'm not overly familiar with q
so it may be done better.
For completeness, here's a version using bluebird
:
var Promise = require('bluebird');
...
var asyncOperationAsPromised = Promise.promisify(asyncOperation);
function performCommand(command) {
console.log('performing command', command);
return asyncOperationAsPromised(command).delay(1000);
}
Promise.each(
[ 'cmd1', 'cmd2', 'cmd3' ],
performCommand.bind(null)
).then(function() {
console.log('all done!');
});