How to write the type of an async pipe function? #196
Replies: 6 comments
-
td;dr It's now in the docs Hi @joshuaavalon, I think it handles it by default: const a = (a1: number) => `${a1}`;
const b = async (a1: string) => [a1];
const pipePromises = <Fns extends F.Function[]>(...fns: F.Piper<Fns>): F.Pipe<Fns> => {
return ((x: any) => fns.reduce((p: any, fn: any) => p.then(fn), Promise.resolve(x))) as F.Pipe<Fns>
}
const t = pipePromises(a, b)(1).then((v: any) => console.log(v)); // ["1"] or even const a = async (a1: number) => `${a1}`;
const b = async (a1: Promise<string>) => [a1];
const pipePromises = <Fns extends F.Function[]>(...fns: F.Piper<Fns>): F.Pipe<Fns> => {
return ((x: any) => fns.reduce((p: any, fn: any) => p.then(fn), Promise.resolve(x))) as F.Pipe<Fns>
}
const t = pipePromises(a, b)(1).then((v: any) => console.log(v)); // ["1"] |
Beta Was this translation helpful? Give feedback.
-
Use |
Beta Was this translation helpful? Give feedback.
-
@pirix-gh I may failed to mention something in my example. The implementation actually unwrap the promise of the result. Consider the following const a = async (a1: number) => `${a1}`;
const b = async (a1: string) => [a1]; This works because JavaScript automatically unwrap promise in |
Beta Was this translation helpful? Give feedback.
-
Yhea, I see what you mean now: import {O, T, F} from 'ts-toolbelt';
const a = async (a1: number) => `${a1}`;
const b = async (b1: Promise<string>) => [b1];
const c = async (c1: Promise<Promise<string>[]>) => [c1];
const pipePromises = <Fns extends F.Function[]>(...fns: F.Piper<Fns>): F.Pipe<Fns> => {
return ((x: any) => fns.reduce((p: any, fn: any) => p.then(fn), Promise.resolve(x))) as F.Pipe<Fns>
}
const t = pipePromises(a, b, c)(1).then((v: any) => console.log(v)); // ["1"] However, this is still correct, but yours unwraps the value as it reduces the list. I'll see what I can think of. I think you'll need a specially crafted type for this. |
Beta Was this translation helpful? Give feedback.
-
@joshuaavalon, good news! You now have an async option that will unwrap the promise types. Check the docs out. And let me know if it's all good :) |
Beta Was this translation helpful? Give feedback.
-
@joshuaavalon did it work out for you? |
Beta Was this translation helpful? Give feedback.
-
🤔 Question
Describe your question
How to write the type of an async pipe function?
Implementation
pipePromises
accepts normal function and async function. I know that the normal pipe function can use<Fns extends F.Function[]>(...args: F.Piper<Fns>): F.Pipe<Fns>
but I don't know how to write the promise version.Search tags, topics
#promise, #async
Beta Was this translation helpful? Give feedback.
All reactions