xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript Promise Time Limit Function All In One

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) {
    try {
      let begin = performance.now();
      let result = await fn(...args);
      let end = performance.now();
      if (end - begin > t) {
        // return Promise.reject(`Time Limit Exceeded`);
        throw new Error(`Time Limit Exceeded`);
      } else {
        return Promise.resolve(result);
      }
    } catch(error) {
      return Promise.reject(error);
    }
  }
};
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 🚀

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

function timeLimit(fn: Fn, t: number): Fn {
  return async function(...args) {
        // const promise = new Promise((resolve, reject) => {
        // - 私有占位符(约定成俗)
        const promise = new Promise((_, reject) => {
            setTimeout(() => {
                reject(`Time Limit Exceeded`);
            }, t);
        });
        return Promise.race([fn(...args), promise]);
    }
}

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

function timeLimit(fn: Fn, t: number): Fn {
  return async function(...args) {
    // const promise = new Promise((resolve, reject) => {
    // - 私有占位符(约定成俗)✅
    // const promise = new Promise((_, reject) => {
    //   setTimeout(() => reject(`Time Limit Exceeded`), t);
    // });
    const promise = new Promise((_, reject) => {
      setTimeout(() => reject(`Time Limit Exceeded`), t);
      // setTimeout(() => Promise.reject(`Time Limit Exceeded`), t); ❌
    });
    return Promise.race([fn(...args), promise]);
  }
}

/* 

Runtime 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".

 */

https://leetcode.com/problems/promise-time-limit/?envType=study-plan-v2&envId=30-days-of-javascript

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/53940043/unhandledpromiserejectionwarning-this-error-originated-either-by-throwing-insid



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2024-05-19 11:24  xgqfrms  阅读(9)  评论(2编辑  收藏  举报