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()
}
})
})
}发布于 2019-02-14 06:22:28
class Network {
constructor() {
this.concurrency = 0
this.pending = []
}
async request(data) {
if (this.concurrency > 10) {
await this.queue();
}
// Make the actual request
// Increment the concurrency count
// call `this.next()` after success of every call
}
queue () {
return new Promise((resolve, reject) => {
this.pending.push({resolve, reject});
})
}
next () {
this.concurrency--;
if (this.concurrency < 10 && this.pending.length) {
let newReq = this.pending.splice(0, 1);
newReq.resolve();
}
}
}https://stackoverflow.com/questions/54684053
复制相似问题