Last active
June 30, 2020 22:30
-
-
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.
This file contains 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
/* | |
* 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