Skip to content

Instantly share code, notes, and snippets.

@janbiasi

janbiasi/microp.js

Created Feb 9, 2016
Embed
What would you like to do?
Micro sized promise library for Node.js and the Browser
(function() {
var root = this;
var giveBackOldPromise = Promise;
var isNode = typeof process === 'object' || window === undefined;
var asap = function(handler) {
if(isNode) {
process.nextTick(handler);
} else {
setTimeout(handler, 1);
}
};
var Promise = (function() {
var STATES = {
RESOLVED: 'resolved',
PENDING: 'pending',
REJECTED: 'rejected'
};
function Promise (target) {
var state = STATES.PENDING;
var value = null;
var deferred = null;
function resolve(updated) {
try {
if(updated && typeof updated.then === 'function') {
updated.then(resolve);
return;
}
value = updated;
state = STATES.RESOLVED;
if(deferred) {
handle(deferred);
}
} catch(notResolvedErr) {
reject(notResolvedErr);
}
}
function reject(reason) {
state = STATES.REJECTED;
value = reason;
if(deferred) {
handle(deferred);
}
}
function handle(handler) {
if(state === STATES.PENDING) {
deferred = handler;
return;
}
asap(function() {
var handlerCallback = undefined;
var result = undefined;
if(state === STATES.RESOLVED) {
handlerCallback = handler.onResolved;
} else {
handlerCallback = handler.onRejected;
}
if(!handlerCallback) {
if(state === STATES.RESOLVED) {
handler.resolve(value);
} else {
handler.reject(value);
}
return;
}
try {
result = handlerCallback(value);
} catch(notHandled) {
handler.reject(notHandled);
return;
}
handler.resolve(result);
});
}
this.then = function(onResolved, onRejected) {
return new Promise(function(resolve, reject) {
handle({
onResolved: onResolved,
onRejected: onRejected,
resolve: resolve,
reject: reject
});
});
};
target(resolve);
};
Promise.prototye = {
noConflict: function(contextual) {
return typeof contextual === 'function' ?
contextual(giveBackOldPromise) :
giveBackOldPromise;
}
};
return Promise;
})();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = Promise;
} else {
window.Promise = Promise;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment