Skip to content

Instantly share code, notes, and snippets.

@paul-bjorkstrand
Last active August 29, 2015 13:56
Show Gist options
  • Save paul-bjorkstrand/9297353 to your computer and use it in GitHub Desktop.
Save paul-bjorkstrand/9297353 to your computer and use it in GitHub Desktop.
// Function.prototype.promisify
(function() {
"use strict";
if (Function.prototype.promisify) {
console.error("Function.prototype.promisify() already exists");
return;
}
var promiseFactory = function(context, f) {
throw "promisify factory not set";
};
Function.prototype.promisify = function(context) {
return promiseFactory(context, this);
};
Function.prototype.promiseCall = function() {
var context = Array.prototype.shift.call(arguments);
return this.promiseApply(context, arguments);
};
Function.prototype.promiseApply = function(context, args) {
return (this.promisify(context)).apply(context, args);
};
window.initPromiseFactory = function(factory) {
promiseFactory = factory;
};
// aliases
Function.prototype.pCall = Function.prototype.promiseCall;
Function.prototype.pApply = Function.prototype.promiseApply;
})();
// Factory Example
(function() {
"use strict";
function jqueryDeferredFactory(context, f) {
return function() {
if (!context) {
context = this;
}
return $.Deferred().resolveWith(context, arguments).then(f);
};
}
window.initPromiseFactory(jqueryDeferredFactory);
})();
// Example #1
(function() {
function retIt(it) {
return it;
}
function printIt(it) {
console.log(it);
}
var retItPromisified = retIt.promisify();
retItPromisified("it").then(printIt);
retIt.promiseCall(null, "it 2").then(printIt);
retIt.promiseApply(null, ["it 3"]).then(printIt);
var csv = "c,s,v";
csv.split.promiseCall(csv, ",").then(printIt);
String.prototype.promiseSplit = String.prototype.split.promisify();
"a,b,c".promiseSplit(",").then(printIt);
})();
// Example #2
(function() {
var original = 5;
function doubleIt(num) { return num * 2; }
function addNine(num) { return num + 9; }
function subtractThree(num) { return num - 3; }
function divideByTwo(num) { return num / 2; }
function subtractOriginal(num) { return num - original; }
function printAndReturnIt(it) {
console.log(it);
return it;
}
printAndReturnIt.promiseCall(null, original)
.then(doubleIt)
.then(printAndReturnIt)
.then(addNine)
.then(printAndReturnIt)
.then(subtractThree)
.then(printAndReturnIt)
.then(divideByTwo)
.then(printAndReturnIt)
.then(subtractOriginal)
.then(printAndReturnIt);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment