// 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))); | |
} | |
} | |
}) | |
} |
// 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