Created
November 17, 2013 08:38
-
-
Save davit-khaburdzania/7510896 to your computer and use it in GitHub Desktop.
simple promises implementation for fun
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
function Promise () { | |
var fail,then, instance, thenCb, failCb, self = this; | |
self.resolve = function (data) { | |
if (thenCb) { | |
thenCb(data); | |
} | |
}; | |
self.reject = function (error) { | |
if (failCb) { | |
failCb(error); | |
} | |
}; | |
instance = { | |
fail: function (cb) { | |
failCb = cb; | |
return self.get(); | |
}, | |
then: function (cb) { | |
thenCb = cb; | |
return self.get(); | |
} | |
}; | |
self.get = function () { | |
return instance; | |
} | |
}; | |
//example usage | |
var fs = require('fs'); | |
function read (name) { | |
var promise = new Promise(); | |
fs.readFile(name , function (error, data) { | |
if (error) { | |
promise.reject(error); | |
} | |
if (data) { | |
promise.resolve(data); | |
} | |
}); | |
return promise.get(); | |
}; | |
read('viri.txt') | |
.then(function (data) { | |
console.log('wow i got data'); | |
}) | |
.fail(function () { | |
console.log('shit failed') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment