-
Notifications
You must be signed in to change notification settings - Fork 0
/
PromiseTimeLimit.ts
38 lines (35 loc) · 1.06 KB
/
PromiseTimeLimit.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const timeLimit = function <T extends (...args: any[]) => Promise<any>>(
fn: T,
t: number
) {
// we have to return modified function
return async function (...args: Parameters<T>) {
let isFinished = false;
return new Promise((resolve, reject) => {
setTimeout(() => {
//if execution is not finished yet then stop execution
if (!isFinished) reject("Time limit exceed");
}, t);
//call original function with received arguments
fn(...args)
.then((data) => {
isFinished = true; //mark execution as finished and resolve with received data
resolve(data);
})
.catch((err) => {
isFinished = true; //mark execution as finished and reject with received error
reject(err);
});
});
};
};
// examples
function myFunction(data: string) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(data);
}, 300);
});
}
const newFunction = timeLimit(myFunction, 500);
newFunction("resolved promise!!").then(console.log).catch(console.log);