Skip to content

Instantly share code, notes, and snippets.

@export-mike
Last active June 30, 2020 22:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save export-mike/ae5955c6917051249a0f9b45a1ef7685 to your computer and use it in GitHub Desktop.
Save export-mike/ae5955c6917051249a0f9b45a1ef7685 to your computer and use it in GitHub Desktop.
compose utility function for async await, A team effort with @cameronbourke and @gwyneplaine. It was a fun discussion.
/*
* Requires Node 8+
* Works in chrome, simply copy and paste into console.
*/
const R = require('ramda');
const compose =
(...funcs) =>
(...args) =>
funcs.reduceRight(async (a, f) => {
if (Array.isArray(a)) {
return await f.apply(undefined, await a);
}
return await f(await a);
}, args)
const get = (v) => {
return Promise.resolve(`${v}s`);
}
const getAllError = compose(
get,
() => Promise.reject('Error! :('),
get,
get
);
const getAll = compose(
get,
get,
get,
get
);
const getAllR = R.composeP(
get,
get,
get,
get
)
async function main() {
try {
const v = await getAllError('ted');
console.log('result', v);
} catch (e) {
console.error(e);
}
try {
const v = await getAll('ted');
console.log('result', v);
} catch (e) {
console.error(e);
}
console.log(await get(await get(await get('ted'))));
console.log(await getAllR('ramda'))
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment