Skip to content

Instantly share code, notes, and snippets.

@allain
Created February 18, 2022 23:30
Show Gist options
  • Save allain/0c44305557da9c896381c68613a79e57 to your computer and use it in GitHub Desktop.
Save allain/0c44305557da9c896381c68613a79e57 to your computer and use it in GitHub Desktop.
Use Promises without unboxing them
// 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