首页 > 编程语言 >JavaScript Promise Time Limit Function All In One

JavaScript Promise Time Limit Function All In One

时间:2024-05-19 11:30:53浏览次数:21  
标签:Function ... return reject JavaScript Promise Time Limit

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 

标签:Function,...,return,reject,JavaScript,Promise,Time,Limit
From: https://www.cnblogs.com/xgqfrms/p/18200162

相关文章

  • HTML 28 - Javascript
    Ascriptisasmallpieceofprogramthatcanaddinteractivitytoourwebsites.Forexample,ascriptcouldgenerateapop-upalertboxmessage,orprovideadropdownmenu.ThisscriptcouldbewrittenusingJavaScriptorVBScript.Nowadays,onlyJavaScr......
  • 在 JavaScript 中保留小数点后两位的方法
    From: https://www.jb51.net/javascript/301602kuw.htm在 JavaScript 中,有多种方法可以保留小数点后两位,本文给大家分享比较常用的方法,文末给大家介绍了实现数据格式化保留两位小数的多种方法,感兴趣的朋友一起看看吧 在JavaScript中,保留小数点后两位的方法在JavaS......
  • 说说JavaScript中的事件模型
    一、事件与事件流javascript中的事件,可以理解就是在HTML文档或者浏览器中发生的一种交互操作,使得网页具备互动性,常见的有加载事件、鼠标事件、自定义事件等由于DOM是一个树结构,如果在父子节点绑定事件时候,当触发子节点的时候,就存在一个顺序问题,这就涉及到了事件流的概念事件......
  • [Javascript] Find Items from the end of the JavaScript Array using at, findLast
    Findingelementsstartingfromtheendofanarrayhasgottenaloteasierwiththeintroductionofthe at, findLast,and findLastIndex methods!With at younolongerneedtoremembertoaccesstheendofthearraylike array[array.length-1] trick.......
  • [Javascript] Object.groupBy & Map.groupBy
    ArrayGrouping isthenewfeatureofJavaScript/ECMAScript,whichsplitsanarray(or,generally,aniterable),intosmallersub-arrays.GroupingisdifferentthanotherJSarraymethods-it's not apartofthearrayprototype,butastaticmethod.......
  • JavaScript中执行上下文和执行栈是什么?
    一、执行上下文简单的来说,执行上下文是一种对Javascript代码执行环境的抽象概念,也就是说只要有Javascript代码运行,那么它就一定是运行在执行上下文中执行上下文的类型分为三种:全局执行上下文:只有一个,浏览器中的全局对象就是 window对象,this 指向这个全局对象函数执行上下......
  • JavaScript object array sort by string bug All In One
    JavaScriptobjectarraysortbystringbugAllInOnebug//purestringsarray,sortOK✅letarr=["banana","strawberry","apple"];JSON.stringify(arr.sort());//'["apple","banana","strawbe......
  • javascript 将变量值作为对象属性 获取对象对应的值
      test(){letform={bar_rule_txt:'{spu}-{master_attr_value}-{slave_attr_alias}',bar_rule_result:'',spu:'JPK1575G',master_attr_value:'黑色',master......
  • JavaScript Object valueOf & toString All In One
    JavaScriptObjectvalueOf&toStringAllInOneclassArrayWrapper{arr:number[];constructor(nums:number[]){this.arr=nums;}//✅改写Object内置方法valueOf,返回一个number整数//❓object相加(本质上是object序列化后的string......
  • AoPS - Chapter 7 Functions
    这一章主要讲解函数的运算与函数方程求解。函数的运算对于函数\(f\),若函数\(g\)满足对任意\(x\)有\(g(f(x))=x\),则\(g\)为\(f\)的反函数(Inverse)。若函数\(h\)满足对于任意\(x\)有\(h(x)=g(f(x))\),则\(h\)为\(f\)与\(g\)的复合(composition),记为\(h=g......