operations.js
operations.js copied to clipboard
Accept promises?
Instead of forcing operations to finish using the done
callback, you could check if the work
function returns a promise. This way you could cleanly wrap all sorts of logic inside an Operation.
I rewrote a rough draft of the _startSingle
function as an example, but I don't understand the codebase enough right now to implement the stuff with queues and composites.
Operation.prototype._startSingle = function() {
var self = this,
called = false;
function payload(payload) {
self.result = payload;
}
function error(err) {
self.error = err;
}
function after() {
called = true;
self.completed = true;
self.running = false;
self._complete();
}
var returned = this.work(function(err, payload) {
if (called) throw "The operation has already completed.";
if (err) error(err);
if (success) success(payload);
after();
});
if (returned && typeof returned.then === 'function') {
returned.then(success, error).always(after);
}
}
Neat idea! I was thinking of providing promises as another alternative to the completion
and onCompletion
event but hadn't thought of this which would tie in nicely!
Let me know if you have any questions on the codebase, I know I could do with adding some comments & tidying up in places ;)
As far as the composites and queues are concerned, I don't think they would require any changes!
The composites just depend on the completion
callback of the suboperations (which is called by your draft above via self._complete();
) and the queues add their own event handler via onCompletion
. So I don't think any changes would be needed anywhere else