Skip to content

Instantly share code, notes, and snippets.

@tjconcept
Last active November 7, 2022 23:08
Show Gist options
  • Save tjconcept/d987a91bcebd22cc03911646baa305c4 to your computer and use it in GitHub Desktop.
Save tjconcept/d987a91bcebd22cc03911646baa305c4 to your computer and use it in GitHub Desktop.
"join" polyfill
export default function using(...args) {
const fn = args.at(-1)
if (typeof fn !== 'function') {
throw new Error('Missing expected function argument')
}
if (args.length < 2) {
throw new Error('At least two arguments must be passed')
}
return Promise.all(args.slice(0, -1)).then((v) => fn(...v))
}
@tjconcept
Copy link
Author

The typeof check might be controversial and diverges from e.g. Bluebird behaviour where e.g. join(1, 2, 3) would be equivalent to Promise.all([1, 2, 3]) (simply returning a promise for an array of the resolved parameters). However, I've seen bugs multiple times caused by the last parameter accidentally being e.g. undefined or null resulting in an array being passed to the next consumer rather than the desired result (often not an array). At the same time, I've rarely (if ever) used the join(1, 2, 3) version (I'd usually favor an object, and argue that a "fixed size" array is a smell that it's not actually a list).

@tjconcept
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment