conveyor.return = Promise.resolve.bind(Promise);
function resolveThenable(thenable, action, self) {
return Promise.resolve(thenable).then(function() {
return action.apply(self, arguments);
});
}
function collectPromiseAction(promise, ret, action, self) {
return promise.then(function() {
return resolveThenable(ret, action, self);
});
}
conveyor.doSequentially = function(actions) {
var promise, i, action, ret, args, self = this;
for (i = 0; i < actions.length; i++) {
action = actions[i];
if (!isFunction(action)) throw new Error('Actions should be functions');
if (ret == null) {
ret = action.apply(self, arguments);
}
else if (isFunction(ret.then) && promise == null) {
promise = resolveThenable(ret, action, self);
}
else if (isFunction(ret.then)) {
promise = collectPromiseAction(promise, ret, action, self);
}
else {
ret = action.apply(self, [ret]);
}
}
return promise || Promise.resolve(ret);
};