I'm currently working on a function that mimics the behavior of Promise.all, except instead of running all promises in parallel, I want to pass an array of callbacks and execute them sequentially. Below is the JavaScript code for my implementation:
function promiseAllSequential(promises) {
return promises.reduce(
(promiseAccumulator, currentPromise) =>
promiseAccumulator.then((resultAccumulator) =>
currentPromise.then((currentResult) => [...resultAccumulator, currentResult])
),
Promise.resolve([])
);
}
The function signature for Promise.all has the following types:
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;
For my function to behave similarly, I believe the signature should be something like this:
promiseAllSequential<FunctionsTuple extends readonly (() => unknown)[] | []>(
functions: FunctionsTuple
): Promise<{
-readonly [TupleIndex in keyof FunctionsTuple]: Awaited<ReturnType<FunctionsTuple[TupleIndex]>>;
}>
However, I am encountering difficulties in getting these types to work with my existing code. The main issue seems to be how to correctly type the reduce function when dealing with a tuple.
I have created a typescript playground highlighting the errors. Additionally, I have attempted to resolve these errors by using numerous type assertions in anothertypescript playground showcasing my best attempt at resolving the issues through multiple hacky assertions.
Is there a feature within TypeScript that could help me achieve this without relying heavily on type assertions?