const urls = [];
for (let i = 1; i <= 10; i++) {
urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`)
}
limitRequest(urls, 3).then(res => {
console.log(res, 999)
})
需要执行 then
,所以一定是 return 一个promise。
function limitRequest(urls, limit) {
return new Promise(resolve => {
function request() {
const url = urls.shift()
if(!url) return
fetch(url).then(res => {
console.log(res);
request()
})
}
// 同时请求三个
request()
request()
request()
})
}
resolve 或 finally 之后都可以直接 .then
function limitRequest(urls, limit) {
return new Promise(resolve => {
let index = 0
function request() {
const url = urls.shift()
if(!url) return
fetch(url).then(res => {
console.log(res);
request()
if(index === 9) { // urls.length
return resolve('all done!')
}
index++
})
}
// 同时请求三个
request()
request()
request()
})
}
request()
request()
request()
可以简化为:
while(limit > 0) {
limit -= 1
request()
}
最终:
function limitRequest(urls, limit = 3) {
return new Promise(resolve => {
let index = 0
function request() {
const url = urls.shift()
if(!url) return
fetch(url).then(res => {
request()
if(index === 9) {
return resolve(‘all done!’)
}
index++
})
}
// 多个同时执行
while(limit > 0) {
request()
limit -= 1
}
})
}