Last active
November 21, 2016 23:32
-
-
Save bkeepers/e6fcc414aef18e303423efe9b92c21a3 to your computer and use it in GitHub Desktop.
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
// Turn any function calls on a promise into function calls on the result. | |
// | |
// For example: | |
// | |
// serialPromise(promise).foo(); | |
// | |
// Is the same as calling: | |
// | |
// promise.then(result => result.foo()); | |
// | |
function serialPromise(promise) { | |
return new Proxy(promise, { | |
get: (target, prop, receiver) => { | |
return function() { | |
return serialPromise(target.then(result => result[prop].apply(this, arguments))); | |
} | |
} | |
}) | |
} |
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
// Define test structure, where promises return objects that return promises | |
let chain = Promise.resolve({ | |
foo: () => Promise.resolve({ | |
bar: () => Promise.resolve({ | |
baz: (x) => { console.log('baz', x)} | |
}) | |
}) | |
}) | |
// Chaining promises manually | |
chain.then(x => x.foo()).then(foo => foo.bar()).then(bar => bar.baz(1)) | |
// Serializing promises | |
serialPromise(chain).foo().bar().baz(2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment