Created
June 26, 2015 13:15
-
-
Save Baudin999/2a30a6e6dd6fb849696e to your computer and use it in GitHub Desktop.
A small promise lib
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
/// Promise.js | |
function Promise() { | |
this.then = function (handler) { | |
this.thenHandler = handler; | |
return this; | |
}; | |
this.error = function (handler) { | |
this.errorHandler = handler; | |
return this; | |
}; | |
} | |
Promise.defer = function () { | |
var promise = new Monad(); | |
return { | |
resolve: function (data) { | |
if (promise.thenHandler) promise.thenHandler(data); | |
}, | |
reject: function (data) { | |
if (promise.errorHandler) promise.errorHandler(data); | |
}, | |
promise: function () { | |
return promise; | |
} | |
} | |
}; | |
module.exports = Promise; | |
/// exmaple.js | |
var Promise = require('./Promise'); | |
function foo() { | |
var deferred = Promise.defer(); | |
setTimeout(function () { | |
deferred.resolve('Hoi'); | |
}, 3000); | |
return deferred.promise(); | |
} | |
function read(path) { | |
var deferred = Promise.defer(), | |
fs = require('fs'); | |
fs.readFile(path, function(err, text) { | |
deferred.resolve(text.toString()); | |
}); | |
return deferred.promise(); | |
} | |
read('./Promise.js') | |
.then(function(_fib) { | |
console.log(_fib); | |
}).error(function(err) { | |
console.log('Something went wrong:', err); | |
}); | |
var promise = foo(); | |
promise.then(function(data) { | |
console.log(data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment