Как создать список ожидающих запросов, в то время как обещание зависает? - PullRequest
0 голосов
/ 14 февраля 2019
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()
        }
    })
  })
}

1 Ответ

0 голосов
/ 14 февраля 2019
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();
    }
  }
}
...