Convert function with callback to Promise
This one uses jQuery, but its whatever really.
by donabrams
HTML
Success:<div id="success"> </div>
Failure:<div id="failure"> </div>
JavaScript
var _ = _ || {};
// This utility function wraps functions that take callbacks (and error handlers) to instead return a Promise.
// By default it just appends the resolve callback to the end of arguments.
// However, you can specify arg indices to overwrite args at the given index.
// If no arguments are given besides fun, the resolve function is appended to args
_.toPromise = function(/* function */ fun, /* boolean */ insert, /* number */ cbIndex, /* number */ errIndex) {
// handle function overloading
var appendToEnd = false;
var addCallback = false;
var addError = false;
var addErrorBeforeCallback = false;
if (typeof insert !== "boolean") {
errIndex = cbIndex;
cbIndex = insert;
insert = false;
}
if (typeof cbIndex === "undefined") {
appendToEnd = true;
} else {
addCallback = cbIndex >= 0;
}
if (typeof errIndex !== "undefined") {
addError = errIndex >= 0;
addErrorBeforeCallback = insert && addError && addCallback && errIndex < cbIndex;
}
return function() {
var dfd = new $.Deferred();
var that = this;
//add the callbacks to the args
if (appendToEnd) {
Array.prototype.push.call(arguments, function() { dfd.resolve.apply(that, arguments);});
}
if (addErrorBeforeCallback) {
Array.prototype.splice.call(arguments, errIndex, 0, function() { dfd.reject.apply(that, arguments);});
}
if (addCallback) {
Array.prototype.splice.call(arguments, cbIndex, insert ? 0 : 1, function() { dfd.resolve.apply(that, arguments);});
}
if (addError && !addErrorBeforeCallback) {
Array.prototype.splice.call(arguments, errIndex, insert ? 0 : 1, function() { dfd.reject.apply(that, arguments);});
}
//call the function
fun.apply(this, arguments);
//return the promise
return dfd.promise();
};
};
// naive test cases
var...