Created
February 18, 2022 23:30
-
-
Save allain/0c44305557da9c896381c68613a79e57 to your computer and use it in GitHub Desktop.
Use Promises without unboxing them
This file contains hidden or 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
// Usage: | |
// console.log(await new PromisedValue([1,2,3]).map(x => x * 2).filter(x => x % 2)) | |
// | |
// instead of this: | |
// console.log(await Promised.resolve([1,2,3]) | |
// .then(arr => arr.map(x => x * 2)) | |
// .then(arr => arr.filter(x => x % 2))) | |
export function PromisedValue(target) { | |
target = Promise.resolve(target) | |
const invoker = (...args) => PromisedValue(target.then((t) => t(...args))) | |
return new Proxy(invoker, { | |
get(_, name) { | |
// passthrough to methods defined on Promise | |
if (typeof target[name] === 'function') return target[name].bind(target) | |
return PromisedValue( | |
target.then((t) => { | |
if (typeof t[name] === 'function') { | |
return (...args) => { | |
let result = t[name].apply(t, args) | |
if (Array.isArray(result)) { | |
result = Promise.all(result) | |
} | |
return PromisedValue(result) | |
} | |
} | |
return t[name] | |
}) | |
) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment