-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise_time_limit.js
More file actions
37 lines (31 loc) · 1.17 KB
/
promise_time_limit.js
File metadata and controls
37 lines (31 loc) · 1.17 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
29
30
31
32
33
34
35
36
// Define the timeLimit function
var timeLimit = function(fn, t) {
return async function(...args) {
const originalFnPromise = fn(...args);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject('Time Limit Exceeded');
}, t);
});
return Promise.race([originalFnPromise, timeoutPromise]);
};
};
// Define the asynchronous function to fetch data from a remote API
const fetchDataFromAPI = async (endpoint) => {
// Simulate fetching data from the API (replace with actual fetch request)
await new Promise(resolve => setTimeout(resolve, 500)); // Simulate delay of 500ms
const response = await fetch(endpoint);
const data = await response.json();
return data;
};
// Usage example:
const timeLimitedFetch = timeLimit(fetchDataFromAPI, 1000); // Set time limit to 1000ms (1 second)
// Call the time-limited function to fetch data from the API
(async()=>{
try {
const data = await timeLimitedFetch('https://jsonplaceholder.typicode.com/posts');
console.log('Data received:', data);
} catch (error) {
console.error('Error:', error);
}
})()