Created
July 2, 2023 04:01
-
-
Save dejanvasic85/07446f6fdd53677bd9abacf62f1658f4 to your computer and use it in GitHub Desktop.
Composing promises in typescript
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
// Here's the original article for function composition and piping: https://blog.logrocket.com/how-to-create-compose-function-typescript/ | |
interface Context { | |
user: string; | |
content: string; | |
} | |
// And this is how to implement the same method using Promises: | |
const compose = <T>(fn1: (a: T) => Promise<T>, ...fns: Array<(a: T) => Promise<T>>) => | |
fns.reduce((prevFn, nextFn) => async (value) => await prevFn(value).then(nextFn), fn1); | |
const addUser = async (ctx: Context): Promise<Context> => { | |
return { | |
...ctx, | |
user: 'user123', | |
}; | |
} | |
const addContent = async (ctx: Context): Promise<Context> => { | |
return { | |
...ctx, | |
content: 'content', | |
} | |
} | |
async function main() { | |
return await compose(addUser, addContent)({ content: '', user: '' }); | |
} | |
main().then(result => { | |
console.log('result', result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment