Skip to content

Instantly share code, notes, and snippets.

@bkeepers
Last active November 21, 2016 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bkeepers/e6fcc414aef18e303423efe9b92c21a3 to your computer and use it in GitHub Desktop.
Save bkeepers/e6fcc414aef18e303423efe9b92c21a3 to your computer and use it in GitHub Desktop.
// 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