首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在允许承诺挂起的同时创建挂起的请求列表?

如何在允许承诺挂起的同时创建挂起的请求列表?
EN

Stack Overflow用户
提问于 2019-02-14 05:56:36
回答 1查看 85关注 0票数 0
代码语言:javascript
复制
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断开了连接.

我最终就是这样做的:

代码语言:javascript
复制
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()
        }
    })
  })
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-14 06:22:28

代码语言:javascript
复制
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();
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54684053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档