Created
February 20, 2013 10:32
-
-
Save damienklinnert/4994595 to your computer and use it in GitHub Desktop.
a promise factory
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
/** | |
* dependencies | |
*/ | |
var q = require('q'); | |
/** | |
* lib | |
*/ | |
// TODO: THINK ABOUT RETURN VALUES AND PARAMS! | |
keeper = (function () { | |
var proto = {}, | |
self = function () { return Object.create(proto); }, | |
promise = q.fcall(function () {}); | |
self.addSync = function (i, fn) { | |
proto[i] = function () { | |
var obj = this, | |
args = arguments; | |
promise = promise.then(function () { | |
return fn.call(obj, args); | |
}); | |
return obj; | |
}; | |
return self; | |
}; | |
self.addAsync = function (i, fn) { | |
proto[i] = function () { | |
var obj = this, | |
args = arguments; | |
promise = promise.then(function () { | |
var deferred = q.defer(); | |
obj.callback = deferred.resolve; | |
fn.call(obj, args); | |
return deferred.promise; | |
}); | |
return obj; | |
}; | |
}; | |
// add error handling function here | |
return self; | |
}()); | |
/** | |
* extend keeper | |
*/ | |
keeper | |
.addSync('setBase', function (base) { | |
console.log('setBase'); | |
}) | |
.addAsync('request', function () { | |
console.log('request'); | |
var that = this; | |
setTimeout(function () { | |
that.callback(); | |
}, 1000); | |
}); | |
/** | |
* usage | |
*/ | |
var dt = keeper() | |
.setBase('base 1') | |
.request() | |
.setBase('base 2'); | |
console.log('before'); | |
var createBaseObject = function () { | |
return keeper() | |
.setBase('asdasd'); | |
}; | |
createBaseObject() | |
.request('asdasdasd'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment