Created
August 16, 2015 04:23
-
-
Save nqbao/4931f4c7c102d5ae8dcf to your computer and use it in GitHub Desktop.
Promise chaining example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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