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