I'm developing a framework in which a particular set of functions could be developed (outside of my control) in a sync or async matter.
In all cases I want to use promises, which is why in the event of an sync method I want to wrap them automatically in an async-function that behaves correctly (as for promise behavior)
I first tried to find a way to guarantee if a method is async or sync, but that' s really brittle (test calling it on initialization to test if a promise is returned, etc... not bullet-proof)
Second try is the following, in which I just wrap any method (sync or async), so no testing required.
Still learning when.js (and getting used to promises in general) so I'd like to get your feedback if this approach would be suitable, see code below:
var aspect = {
f: function(){
//function may be sync or async this is unknown.
}
};
aspect.f = (function (origf) {
return function(){
var deferred = when.defer();
when(origf, function(){
deferred.resolve();
}).otherwise(function(err){
deferred.reject(err);
});
return deferred.promise;
};
}(aspect.f));
To my understanding, whether a 'origf'' is async or not, this will create an async function that resolves correctly.
Moreover an async 'origf' may do a reject() in which case the wrapper picks it up.
still not sure, how to handle the case (out of my control) when an sync 'origf' throws an error (explicitly designed or unanticipated)
So in short, would this be a correct approach? And better yet, how to handle the 'sync 'origf' throw error' -case?
Thanks,
Geert-Jan