Skip to content

Instantly share code, notes, and snippets.

@thejhh
Created December 27, 2013 10:56
Show Gist options
  • Select an option

  • Save thejhh/8145497 to your computer and use it in GitHub Desktop.

Select an option

Save thejhh/8145497 to your computer and use it in GitHub Desktop.
Proof of concept of function-based promise (wrapper) implementation
// The (wrapper) implementation of function based promise
var Q = require('q');
var foo = {};
foo.sum = function(a, b) {
function wrap_p(p) {
function f() {
var args = Array.prototype.slice.call(arguments);
return wrap_p(p.then.apply(p, args));
};
f.then = p.then.bind(p);
f.fail = p.fail.bind(p);
f.done = p.done.bind(p);
return f;
}
var p = Q.fcall(function() {
console.log("foo.sum(" + a + ", " + b + ")");
return a + b;
});
return wrap_p(p);
};
// The normal example
foo.sum(10, 10).then(function(x) {
return x+10;
}).then(function(x) {
return x*x;
}).then(function(x) {
console.log('Result: ' + x);
}).fail(function(err) {
console.error("Error: " + err);
}).done();
// The new style
foo.sum(10, 10)(function(x) {
return x+10;
})(function(x) {
return x*x;
})(function(x) {
console.log('Result: ' + x);
}).fail(function(err) {
console.error("Error: " + err);
}).done();
// The output:
//
// $ node chain-test.js
// foo.sum(10, 10)
// foo.sum(10, 10)
// Result: 900
// Result: 900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment