Created
August 31, 2013 16:52
-
-
Save kbjr/6399396 to your computer and use it in GitHub Desktop.
An extension to oath that would simplify creating/returning/passing promises.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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