Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Created July 2, 2023 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejanvasic85/07446f6fdd53677bd9abacf62f1658f4 to your computer and use it in GitHub Desktop.
Save dejanvasic85/07446f6fdd53677bd9abacf62f1658f4 to your computer and use it in GitHub Desktop.
Composing promises in typescript
// 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