JavaScript Promise Time Limit Function All In One

xgqfrms發表於2024-05-19

JavaScript Promise Time Limit Function All In One

LeetCode 2637. Promise Time Limit

errors

function timeLimit(fn: Fn, t: number): Fn {
  return async function (...args) {
    // let begin = Date.now();
    let begin = performance.now();
    let result = await fn(...args);
    // let end = Date.now();
    // let end = performance.now();
    // if (end - begin > t) {
    if (performance.now() - begin > t) {
      // throw new Error(`Time Limit Exceeded`);
      // ❌ catch error
      return Promise.reject(`Time Limit Exceeded`);
    } else {
      return Promise.resolve(result);
    }
    // console.log(`end - begin`, end - begin, t);
    // try {
    //   if (end - begin > t) {
    //     return Promise.reject(`Time Limit Exceeded`);
    //   } else {
    //     return Promise.resolve(result);
    //   }
    // } catch(error) {
    //   throw error;
    // }
  }
};

// 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 "Time Limit Exceeded". ❌

/**
 * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
 * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
 */
function timeLimit(fn: Fn, t: number): Fn {
  return async function (...args) {
    let id = setTimeout(() => {
      // throw Error(`Time Limit Exceeded`);
      // return Promise.reject(`Time Limit Exceeded`);
      throw new Error(`Time Limit Exceeded`);
    }, t);
    let result = await fn(...args);
    clearTimeout(id);
    return result;
    // return Promise.resolve(result);
  }
};

solutions

new Promise wrap function

type Fn = (...params: any[]) => Promise<any>;

function timeLimit(fn: Fn, t: number): Fn {
  return async function (...args) {
    // new Promise wrap ✅
    return new Promise((resolve, reject) => {
      setTimeout(() => {
       reject(`Time Limit Exceeded`);
      }, t);
      // ❓ thenable & catch error
      //fn(...args).then(result => resolve(result)).catch(error => reject(error));
      // shorthand 🚀
      fn(...args).then(resolve).catch(reject);
    })
  }
};

image

type Fn = (...params: any[]) => Promise<any>;

function timeLimit(fn: Fn, t: number): Fn {
  return async function (...args) {
    // new Promise wrap ✅
    return new Promise((resolve, reject) => {
      let timeId= setTimeout(() => {
       reject(`Time Limit Exceeded`);
      }, t);
      // ❓ thenable & catch error
      //fn(...args).then(result => resolve(result)).catch(error => reject(error)).finally(() => clearTimeout(timeId));
      // shorthand 🚀
      fn(...args).then(resolve).catch(reject).finally(() => clearTimeout(timeId));
    })
  }
};

demos

Promise.race

/**
 * @param {Function} fn
 * @param {number} t
 * @return {Function}
 */
var timeLimit = function(fn, t) {
  return async function(...args) {
        const originalFnPromise = fn(...args);
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => {
                reject('Time Limit Exceeded')
            }, t);
        })
        return Promise.race([originalFnPromise, timeoutPromise]);
    }
};

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個資訊, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 檢視原創文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 釋出文章使用:只允許註冊使用者才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


相關文章