Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Created April 3, 2021 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/7e255a19320af56d3d7e75465afb597b to your computer and use it in GitHub Desktop.
Save zhongyangxun/7e255a19320af56d3d7e75465afb597b to your computer and use it in GitHub Desktop.
限制并发请求数量的方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Concurrent request</title>
</head>
<body>
<button id="fetch">fetch</button>
<script>
function handleFetchQueue(urls, max, callback) {
const finMap = new Map();
const requestCount = urls.length;
const resList = [];
let next = -1;
let requesting = 0;
const request = (i) => {
requesting++;
fetch(urls[i])
.then((data) => {
resList[i] = data;
})
.catch((err) => {
resList[i] = err;
})
.finally(() => {
finMap.set(i, 1);
requesting--;
if (finMap.size === requestCount) {
callback(resList);
} else if (requesting < max) {
next++;
if (next < requestCount) {
request(next);
}
}
});
};
while (requesting < max) {
next++;
request(next);
}
}
const dogTypes = [
'affenpinscher',
'african',
'airedale',
'akita',
'appenzeller',
'basenji',
'beagle',
'bluetick',
'borzoi',
'bouvier',
];
const urls = dogTypes.map(
(type) => `https://dog.ceo/api/breed/${type}/images/random`
);
const btn = document.getElementById('fetch');
btn.addEventListener('click', function () {
handleFetchQueue(urls, 2, (res) => {
console.log(res);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment