【问题标题】:Typescript function with function as parameter以函数为参数的打字稿函数
【发布时间】:2021-09-06 12:42:24
【问题描述】:

我想创建一个将任务重复一定次数的通用函数。它应该接收另一个函数并按照用户的意愿重复它 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
) { }

问题是无法调用转发器函数并使用我的可选参数传递要重复的函数:

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

我收到错误:

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

它只能这样工作:

const tasksResults = await executeTask(executeSpeedTest, 3);

我正在努力研究如何使用一个包装函数来重复任何其他函数并且仍然能够传递内部函数参数。

非常感谢。

【问题讨论】:

    标签: typescript typescript-decorator


    【解决方案1】:

    这样运行代码怎么样?

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

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

    await executeTask(executeSpeedTest(18104))
    

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

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

    【讨论】:

    • 很高兴它有帮助!如果您可以将我的答案标记为正确答案,那将有助于未来的读者找到问题!
    • 我仍然没有足够的声望来投票。
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2019-09-20
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多