Skip to content

Instantly share code, notes, and snippets.

@ZJONSSON
Last active December 18, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZJONSSON/5727022 to your computer and use it in GitHub Desktop.
Save ZJONSSON/5727022 to your computer and use it in GitHub Desktop.
Minimalistic Promises A+ framework (without setTimeout/nextTick. 2 of 231 test fail)
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]);
}
};
}
};
// 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