Skip to content

Instantly share code, notes, and snippets.

@nqbao
Created August 16, 2015 04:23
Show Gist options
  • Save nqbao/4931f4c7c102d5ae8dcf to your computer and use it in GitHub Desktop.
Save nqbao/4931f4c7c102d5ae8dcf to your computer and use it in GitHub Desktop.
Promise chaining example
// proof of concept for promise chaining
function chain(obj) {
let stack = [];
let proxy = new Proxy(obj, {
get: (target, name, receiver) => {
if (name == 'finally' || name == "done") {
return function(callback) {
return replayStack(obj, stack, callback);
}
}
else {
return function() { stack.push([name, arguments]); return proxy; }
}
}
});
return proxy;
}
let replayStack = function(obj, stack, done) {
let then = function(promise, obj, next) {
return promise.then(function(result) {
if (typeof result != 'object') {
result = obj; // keep the chain
}
return result[next[0]].apply(result, next[1]);
});
}
let promise = new Promise((resolve, reject) => {
resolve(obj);
});
for (let next of stack) {
promise = then(promise, obj, next);
}
return promise.then(done);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment