-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChallenge_29.js
34 lines (32 loc) · 969 Bytes
/
Challenge_29.js
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
function raceWithTimeout(promises, timeout) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => reject(new Error('Timeout')), timeout);
promises.forEach((promise) => {
promise.then(
(value) => {
clearTimeout(timeoutId);
resolve(value);
},
(error) => {
clearTimeout(timeoutId);
reject(error);
}
);
});
});
}
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve(5), 1000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Error!')), 500);
});
// done 29 challenge
raceWithTimeout([promise1, promise2, promise3], 700)
.then((value) => {
console.log('The first promise to resolve was:', value);
})
.catch((error) => {
console.error('Error:', error);
});