Last active
December 18, 2015 04:39
-
-
Save ZJONSSON/5727022 to your computer and use it in GitHub Desktop.
Minimalistic Promises A+ framework (without setTimeout/nextTick. 2 of 231 test fail)
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
var promin = require("promin"); | |
module.exports.adaptor = { | |
fulfilled: function(value) { return promin().set(true, [value]); }, | |
rejected: function(reason) { return promin().set(false, [reason]); }, | |
pending: function() { | |
var p = promin(); | |
return { | |
promise: p, | |
fulfill: function(value) { | |
p.set(true, [value]); | |
}, | |
reject: function(reason) { | |
p.set(false, [reason]); | |
} | |
}; | |
} | |
}; | |
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
// Based on https://github.com/timjansen/PinkySwear.js.git | |
function isFn(f,o) { return typeof f == 'function'; } | |
function Promin() {} | |
Promin.prototype = { | |
set : function(state,values) { | |
if (!this.state) { | |
this.state = state; | |
this.values = [].concat(values); | |
if (this.deferred && this.deferred.length) this.deferred.forEach(function(s) { | |
then.apply(this,s); | |
},this); | |
} | |
return this; | |
}, | |
then : function(d,e) { | |
var p = new Promin(); | |
this.deferred = this.deferred || []; | |
if (this.state !== undefined) then.call(this,d,e,p); | |
else this.deferred.push([d,e,p]); | |
return p; | |
} | |
}; | |
function then(d,e,p) { | |
var self = this; | |
try { | |
var f = (self.state ? d : e); | |
if (isFn(f)) { | |
var r = f.apply(null,self.values); | |
if (r && isFn(r.then)) | |
r.then(function(d) { return p.set(true,d);},function(d) { return p.set(false,d);}); | |
else | |
p.set(true,r); | |
} | |
else | |
p.set(self.state,self.values); | |
} | |
catch(e) { | |
p.set(false,[e]); | |
} | |
} | |
module.exports = function() { | |
return new Promin(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment