Skip to content

Instantly share code, notes, and snippets.

@munro
Created March 29, 2012 19:29
Show Gist options
  • Save munro/2242674 to your computer and use it in GitHub Desktop.
Save munro/2242674 to your computer and use it in GitHub Desktop.
Lazier Functional Promise
/**
* 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