Skip to content

Instantly share code, notes, and snippets.

@kbjr
Created August 31, 2013 16:52
Show Gist options
  • Save kbjr/6399396 to your computer and use it in GitHub Desktop.
Save kbjr/6399396 to your computer and use it in GitHub Desktop.
An extension to oath that would simplify creating/returning/passing promises.
function promises(func) {
var promiseIndex = func.length - 1;
return function() {
var scope = this;
var args = Array.prototype.slice.call(arguments);
var promise = args[promiseIndex] = args[promiseIndex] || new oath();
process.nextTick(function() {
func.apply(scope, args);
});
return promise.promise || promise;
};
}
// -------------------------------------------------------------
// Define a function as one that uses a promise. The promise will be created
// if not given when the function is called, and automatically returned
var doFoo = promises(function(promise) {
doSomething(function(err, results) {
if (err) {
return promise.reject(err);
}
promise.resolve(results);
});
});
// Promise created and returned automatically
doFoo().then(...);
// Passing in your own promise, possibily from somewhere else
doFoo(new oath()).then(...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment