// 延时封装
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function processWithConcurrency(tasks, concurrencyLimit) {
const results = []
const excuting = new Set()
for (const task of tasks) {
const taskResponse = Promise.resolve().then(() => {
task()
})
results.push(taskResponse)
if (concurrencyLimit <= tasks.length) {
const e = taskResponse.then(() => excuting.delete(e))
excuting.add(e)
if (excuting.size >= concurrencyLimit) {
await Promise.race(excuting)
}
}
}
return Promise.all(results)
}
// 执行
async function fetchApiData(url) {
await delay(1000)
return `response from ${url}`
}
const urls = [
'https://examp1.api.com',
'https://examp2.api.com'
]
const tasks = urls.map(url => {
return () => {
fetchApiData(url)
}
})
processWithConcurrency(tasks, 2).then(results => {
// console.log(results)
})
console