const fetch = (url, time) => {
return function() {
return new Promise(resolve => {
setTimeout(() => {
resolve(url);
}, time)
})
}
}
function fetchLimit(tasks, limit = 2) {
let count = 0;
const result = [];
const len = tasks.length;
return new Promise((resolve, reject) => {
function run() {
if (tasks.length && count < limit) {
count++;
const fn = tasks.shift();
fn().then(item => {
count--;
result.push(item);
if (result.length === len) {
resolve(result);
} else {
run();
}
}).catch(err => {
reject(err);
})
}
}
for (let i = 0; i < tasks.length; i++) {
run();
}
})
}
const tasks = [
fetch('this-1', 1000),
fetch('this-2', 2000),
fetch('this-3', 3100),
fetch('this-4', 1000),
fetch('this-5', 1000),
fetch('this-6', 2000),
fetch('this-7', 1000),
fetch('this-8', 1000),
]
fetchLimit(tasks).then(res => {
console.log('res: ', res);
});
console