class Network {
constructor() {
this.concurrency = 0
this.pending = []
}
request(data) {
if (this.concurrency <= 10) {
++this.concurrency
return request({
...data
}).finally(res =>{
--this.concurrency
this.pending.forEach(data => {
this.request(data)
})
return res
})
} else {
this.pending.push(data)
return new Promise(...)
}
}
}
То, что я пытаюсь сделать, - это ограничить одновременный запрос до 10 и разрешить чрезмерный запрос поставить в очередь и возвращать ожидающее обещание до тех пор, пока одновременный запрос не упадет с 10 ...
Очевидно,приведенный выше код не будет работать, потому что this.pending
отключен от new Promise
...
Вот как я это сделал в конце концов:
class Network {
constructor() {
this.concurrency = 0
this.pending = []
}
ajax = data => new Promise(resolve => {
if (this.concurrency <= 10) {
++this.concurrency
return resolve( this.send(data) )
} else {
return this.pending.push({ data, resolve })
}
})
send = data => new Promise(resolve => {
return request({
...data
}).finally(res => {
--this.concurrency
if (this.pending.length)
for (let request of this.pending) {
request.resolve( this.ajax(request.data) )
this.pending.shift()
}
})
})
}