0

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.

1 Answer 1

1

How about running the code like this?

const tasksResults = await executeTask(() => executeSpeedTest(18104), 3);

This should work, since it's passing in a function that your executeTask function will call. The reason it doesn't work like this:

await executeTask(executeSpeedTest(18104))

is because you are calling executeSpeedTest when that line is executed, meaning it is taking the result of executeSpeedTest, which in this case appears to be a Promise.

Switching to the arrow function will ensure the code is only called when your calling function calls task().

Sign up to request clarification or add additional context in comments.

2 Comments

Glad it helped! If you could mark my answer as the correct answer, that'd help future readers find the question!
I still don't have enough reputation to cast a vote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.