I want to create a generic function that repeats tasks a certain number of times. It should receive another function and repeate it x times as the user wishes.
My generic function:
export async function executeTask(task: (...args: any[]) => any, times: number) {
// Validate the repeat parameter
if (times <= 0 || !Number.isInteger(times))
throw new Error('The repeat parameter should be a positive integer.');
// Tasks promises results
const tasksResults: Promise<any>[] = [];
// Initialize the repeat counter
let cycle = 0;
while (cycle < times) {
cycle++;
// Add each task promise to the promises array
tasksResults.push(task());
}
// Only return when all promises has resolved
return Promise.all(tasksResults);
}
But the function I want to repeat has some optional parameters. See the func. signature:
export async function executeSpeedTest(
targetServerId?: number,
outputFormat?: OutputFormat,
outputUnit?: OutputUnit,
showProgress?: boolean
) { }
The issue is that cannot call the repeater function and pass the function to be repeated with my optional params:
const tasksResults = await executeTask(executeSpeedTest(18104), 3);
I receive the error:
Argument of type 'Promise' is not assignable to parameter of type '(...args: any[]) => any'. Type 'Promise' provides no match for the signature '(...args: any[]): any'.ts(2345)
It only works like this:
const tasksResults = await executeTask(executeSpeedTest, 3);
I'm struggling on how I can use one wrapper function to repeat whatever other function and still being able to pass the inner function parameters.
Thank you very much.