Created
March 29, 2012 19:29
-
-
Save munro/2242674 to your computer and use it in GitHub Desktop.
Lazier Functional Promise
This file contains 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
/** | |
* Functional promise | |
*/ | |
var Promise = (function createPromise(listeners, resolved) { | |
var self = this; | |
if (typeof listeners === 'undefined') { | |
listeners = []; | |
} | |
function resolve() { | |
var args = Array.prototype.slice.call(arguments, 0); | |
listeners.forEach(function (fn) { | |
fn.apply(this, args); | |
}) | |
return createPromise([], args); | |
} | |
resolve.done = function () { | |
return function (fn) { | |
if (typeof resolved !== 'undefined') { | |
fn.apply(this, resolved); | |
return self; | |
} | |
return createPromise(listeners.concat([fn])); | |
}; | |
}; | |
return resolve; | |
}()); | |
/** | |
* Do manad | |
*/ | |
function doMonad() { | |
var args = arguments; | |
return function () { | |
Array.prototype.reduceRight.call(args, function (prev, curr) { | |
if (typeof prev === 'undefined') { | |
return curr; | |
} else { | |
return curr(prev); | |
} | |
}); | |
}; | |
} | |
/** | |
* Testing side effect free asyncronous function with a monad | |
*/ | |
function getUsers() { | |
return function (resolve) { | |
setTimeout(function () { | |
resolve('Hello, world!'); | |
}, 1000); | |
}; | |
} | |
doMonad( | |
getUsers(), | |
Promise.done(), | |
function (data) { | |
console.log('Data!!!!', data); | |
} | |
)(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment