-
-
Save Davis-Desormeaux/2626934 to your computer and use it in GitHub Desktop.
Functional Promise
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
/** | |
* 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 (fn) { | |
if (typeof resolved !== 'undefined') { | |
fn.apply(this, resolved); | |
return self; | |
} | |
return createPromise(listeners.concat([fn])); | |
}; | |
return resolve; | |
}()); | |
/** | |
* Do manad | |
*/ | |
function doMonad() { | |
Array.prototype.reduceRight.call(arguments, 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); | |
}).done(function (data) { | |
console.log('Foo', data); | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment