Created
August 12, 2014 20:43
-
-
Save FireNeslo/a094e06ed61b0af35ffb to your computer and use it in GitHub Desktop.
This file contains hidden or 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 (root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define([], factory); | |
} else if (typeof exports === 'object') { | |
module.exports = factory(); | |
} else { | |
root.Promise = factory(); | |
} | |
}(this, function () { | |
function Promise(init) { | |
var state = -1, queue = [], value; | |
function fulfill(state, value, handler) { | |
if(state < 0) {return;} | |
while(handler=queue.pop()) handler[state](value); | |
} | |
function resolve(val) { | |
state < 0 && fulfill(state=0,value=val); | |
} | |
function reject(val) { | |
state < 0 && fulfill(state=1,value=val); | |
} | |
function handle(handler, res, rej) { | |
return function(val) { | |
if(handler){ | |
try {val = handler(value)} | |
catch(e){return rej(e);} | |
} | |
if (val && val.then) { return val.then(res, rej) } | |
state > 0 ? rej(val) : res(val) | |
}; | |
} | |
this.then = function(success, fail) { | |
return new Promise(function(res, rej) { | |
queue.push([handle(success, res, rej),handle(fail, res, rej)]) | |
fulfill(state, value); | |
}); | |
}; | |
init(resolve, reject); | |
} | |
Promise.prototype.catch = function(fail) { | |
return this.then(null, fail); | |
}; | |
Promise.resolve = function(promise) { | |
if(promise instanceof Promise) {return promise} | |
return new Promise(function(resolve, reject) { | |
promise && promise.then | |
? promise.then(resolve, reject) | |
: promise instanceof Error | |
? reject(promise) | |
: resolve(promise) | |
}) | |
} | |
Promise.defer = function() { | |
var defer = {}; | |
defer.promise = new Promise(function(resolve, reject) { | |
defer.resolve = resolve; | |
defer.reject = reject; | |
}) | |
return defer; | |
}; | |
Promise.all = function(array) { | |
var result = []; | |
return new Promise(function(resolve, reject) { | |
if(!array.length) {resolve(result); } | |
function accumulate(value) { result.push(value) === array.length && resolve(result);} | |
array.forEach(function(promise) {Promise.resolve(promise).then(accumulate, reject);}); | |
}); | |
}; | |
return Promise; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment