JSFiddle - React, Tailwind, and code Playground
by taylorbuley
JavaScript
var deferred = function () {
var complete = false,
wasSuccess = null,
completed = [],
children = [],
notifies = [],
successes = [],
errors = [],
safeApply = function (fn, args, context, err) {
if (isFunction(fn)) {
return fn.apply(context || {}, args || []);
}
if (isFunction(err)) {
return safeApply(err, []);
}
}, safeEach = function (items, callback, inc) {
var x,
count = items.length;
inc = inc || 1;
for (x = 0; x < count; x += inc) {
safeApply(callback, [items[x], x]);
}
}, is = function (a, b) {
return b === a;
}, isFunction = function (mixed_var) {
return isType("function", mixed_var);
}, isType = function (str, mixed_var) {
return is(str, typeof mixed_var);
};
return {
'promise': function (on_success, on_error, on_notify) {
var defd = deferred();
children.push(deferred);
if (is(complete, true)) {
safeApply(wasSuccess ? on_success : on_error, completed);
}
safeEach([
[successes, on_success],
[errors, on_error],
[notifies, on_notify]
], function (pair) {
var fn = pair[1];
if (isFunction(fn)) {
pair[0].push(fn);
}
});
return defd.promise;
},
'resolve': function () {
var args = arguments;
wasSuccess = true;
complete = true;
completed = args;
safeEach(successes, function (on_success) {
safeApply(on_success, args);
});
safeEach(children, function (child) {
safeApply(child.resolve, args);
});
...