如何在允许诺言挂起的同时创建待处理的请求列表?

时间:2019-02-14 05:56:37

标签: javascript promise es6-promise

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.pendingnew 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()
        }
    })
  })
}

1 个答案:

答案 0 :(得分:0)

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();
    }
  }
}