-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiTimeLimit.js
More file actions
28 lines (24 loc) · 1.27 KB
/
Copy pathapiTimeLimit.js
File metadata and controls
28 lines (24 loc) · 1.27 KB
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
/*
Create a function called enforceTimeLimit that takes an API request function apiFn and an integer timeLimit, representing the maximum allowed execution time. The apiFn is generated using the functionGenerator method from a helper class, which accepts apiResponse and executionTime as parameters. The aim is to return a modified version of apiFn that respects the specified time limit. If apiFn runs longer than the given timeLimit, it should be terminated or rejected.
*/
function enforceTimeLimit(apiFunc, timeLimit) {
// solution 1 (classic)
// return function(...args) {
// return new Promise((resolve, reject) => {
// const timer = setTimeout(() => reject("Timelimit exceeded"), timeLimit);
// apiFunc.call(this, ...args)
// .then(resp => resolve(resp))
// .catch(err => reject(err))
// .finally(() => clearTimeout(timer))
// })
// }
// solution 2 (modern)
return function(...args) {
let timer;
const timerPromise = new Promise((_, reject) => {
timer = setTimeout(() => reject("Timelimit exceeded"), timeLimit);
});
return Promise.race([timerPromise, apiFunc.call(this, ...args)])
.finally(() => clearTimeout(timer));
}
}