Created
March 30, 2017 13:21
-
-
Save mrmlnc/17b98f0a8bc57f4598b2947a955e2843 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mockupFetch(cache: object, url: stirng) { | |
return new Promise((resolve) => { | |
if (cache.hasOwnProperty(url)) { | |
return resolve(cache[url]); | |
} | |
setTimeout(() => { | |
const date = new Date(); | |
const min = date.getMinutes(); | |
const sec = date.getSeconds(); | |
resolve(`${min}:${sec}-${url}`); | |
}, 1000); | |
}); | |
} | |
function parallelFetch(urls: string[], limit: number, cb: Function) { | |
const cache: object = {}; | |
let workIndex= 0; | |
let total = 0; | |
if (urls.length < limit) { | |
limit = urls.length; | |
} | |
function request(index: number) { | |
const url = urls[index]; | |
workIndex++; | |
total++; | |
mockupFetch(cache, url) | |
.then((res) => { | |
cache[url] = res; | |
total--; | |
if (total < limit && workIndex < urls.length) { | |
request(workIndex); | |
} else if (total === 0) { | |
cb(urls.map((url) => cache[url])); | |
} | |
}); | |
} | |
while (workIndex < limit) { | |
request(total); | |
} | |
} | |
parallelFetch( | |
['a', 'b', 'c', 'a', 'd'], | |
1, | |
console.log | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment