给定异步函数,需要帮助尝试编写一个函数来返回输入函数的新的限时版本

问题描述 投票:0回答:1

以下是挑战方向:

给定一个异步函数 fn 和一个以毫秒为单位的时间 t,返回输入函数的新的限时版本。 fn 接受提供给限时函数的参数。

限时功能应遵循以下规则:

  • 如果 fn 在 t 毫秒的时间限制内完成,则时间限制函数应解析结果。
  • 如果 fn 的执行超过时间限制,则时间限制函数应拒绝并显示字符串“Time Limit Exceeded”。

我已经尝试过这两段代码:

// Function to return new time limited version of input function
const timeLimit = function(fn, t) {

    // Outer asynchronous function
    async function timeLimited(...args) {

        // Set start time to current time
        let startTime = Date.now()

        // Wait to get fulfillment value from function parameter
        const result = await fn(...args);

        // Duration will be current time minus the start time
        let duration = Date.now() - startTime;

        /* If duration is greater than the time parameter,
           throw time limit excession error */
        if (duration > t) throw new Error("Time Limit Exceeded");

        // Else return the result of the await function
        else return result;

    };

    // Return the asynchronous time-limited function
    return timeLimited; };

但我明白了:

输出:

{"rejected":{},"time":100}

预期:

{"rejected":"Time Limit Exceeded","time":50}
// Function·to·return·new·time·limited·version·of·input·function
const timeLimit = function(fn, t) {

    // Boolean to say error is false or true
    let hasError = false;

    // Outer asynchronous function
    async function timeLimited(...args) {

        // Set timer ID
        const timerId = setTimeout(() => hasError = true, t);

        // Constant to hold result
        const result = fn(...args);

        // Clear timeout
        clearTimeOut(timerId);

        // If there is an error, throw it
        if (hasError) throw new Error("Time Limit Exceeded");

        // Else return the result of the await function
        else return result;

    };

    // Return time limited function
    return timeLimited; };

但我明白了:

运行时错误

(node:21) Warning: Accessing non-existent property 'ListNode' of module exports inside circular dependency
(Use `nodejs run --trace-warnings ...` to show where the warning was created)
(node:21) Warning: Accessing non-existent property 'TreeNode' of module exports inside circular dependency
(node:21) Warning: Accessing non-existent property 'NestedInteger' of module exports inside circular dependency
node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
Node.js v20.10.0

以下是测试用例:

const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
limited(150).catch(console.log); // "Time Limit Exceeded" at t=100ms

如果有人可以帮助我修复我的代码,我将不胜感激。

javascript node.js asynchronous promise timeout
1个回答
0
投票

您必须创建自己的自定义错误消息,如下所示:

const timeLimit = function (fn, t) {
  async function timeLimited(...args) {
    let startTime = Date.now();
    const result = await fn(...args);
    let duration = Date.now() - startTime;
    if (duration > t) throw new CustomError("Time Limit Exceeded", duration);
    else return result;
  }

  return timeLimited;
};

function CustomError(message, duration) {
  return {
    rejected: new Error(message).message || "",
    duration: duration,
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.