Skip to content

Instantly share code, notes, and snippets.

@mrmlnc
Created March 30, 2017 13:21
Show Gist options
  • Save mrmlnc/17b98f0a8bc57f4598b2947a955e2843 to your computer and use it in GitHub Desktop.
Save mrmlnc/17b98f0a8bc57f4598b2947a955e2843 to your computer and use it in GitHub Desktop.
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