-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestModule2.js
66 lines (54 loc) · 1.54 KB
/
testModule2.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const promises = [
'url',
'url2',
'url2',
'url2',
'url2',
'url6',
];
async function getResult(urls) {
// return Promise.resolve([{"status": "resolved", "value": 42}, {"status": "rejected", "reason": "nope"}]);
let results = []
let ferst5 = urls.slice(0, 4);
const race5 = await Promise
.race(ferst5.map(async url => ({
res: await fetch(url),
url
})))
.then(res => res)
results.push(race5)
if (urls.length > 0) {
results = [...results, ...(await getResult(urls.filter(url => url !== race5.url))) ]
}
return results;
}
function getResults2(urls) {
const results = [];
let urlQueue = urls
.slice(0, 4)
.map(url => ({promise: fetch(url), url}));
return Promise
.race(urlQueue.map(({promise}) => promise))
.then(raceSubscriber({results, urlQueue, urls}));
}
const raceSubscriber = ({results, urlQueue, urls}) => res => {
results.push(res.data);
urlQueue = urlQueue.map(({url, promise}) => {
if (url === res.url) {
return new Promise(async resolve => {
const newUrl = urls[4 + results.length];
const promise = await fetch(newUrl);
resolve({
url: newUrl,
promise,
});
});
}
return {url, promise};
});
if (urlQueue.length) {
return Promise.race(urlQueue)
.then(raceSubscriber({results, urlQueue, urls}));
}
return results;
};