以函数为参数的打字稿函数

时间:2021-06-22 23:21:03

标签: typescript typescript-decorator

我想创建一个将任务重复一定次数的通用函数。它应该接收另一个函数并按照用户的意愿重复执行 x 次。

我的通用函数:

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);
}

但是我要重复的函数有一些可选参数。见函数。签名:

export async function executeSpeedTest(
    targetServerId?: number,
    outputFormat?: OutputFormat,
    outputUnit?: OutputUnit,
    showProgress?: boolean
) { }

问题是无法调用repeater函数并通过我的可选参数传递要重复的函数:

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

我收到错误:

<块引用>

'Promise' 类型的参数不能分配给 '(...args: any[]) => any' 类型的参数。类型 'Promise' 不匹配签名 '(...args: any[]): any'.ts(2345)

它只能这样工作:

const tasksResults = await executeTask(executeSpeedTest, 3);

我正在苦苦思索如何使用一个包装函数来重复任何其他函数,并且仍然能够传递内部函数参数。

非常感谢。

1 个答案:

答案 0 :(得分:1)

像这样运行代码怎么样?

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

这应该可以工作,因为它传入了一个您的 executeTask 函数将调用的函数。它不能像这样工作的原因:

await executeTask(executeSpeedTest(18104))

是因为您在执行该行时调用 executeSpeedTest,这意味着它正在获取executeSpeedTest结果,在这种情况下似乎是 Promise

切换到箭头函数将确保仅在调用函数调用 task() 时调用代码。