【问题标题】:Queuing Promises (ES6)队列承诺 (ES6)
【发布时间】:2018-11-28 16:07:19
【问题描述】:

我正在编写一个从 API 请求数据的 NodeJS 服务。在负载下,我不想用可能有数百个同时请求来敲击 API,所以我试图将请求排队,以便它们一个接一个地执行,并且它们之间存在延迟。

const request = require( 'request' );
class WebService {
  constructor() {
    this.RequestQueue = [];
  }

  _Get( uri, options, reply ) {
    return new Promise( ( resolve, reject ) => {
      request.get( uri, options, ( err, resp, body ) => {
        if ( err )
          reject( err );

        reply( resp );
        resolve( resp );
      } );
    } );
  }

  async onRequest( data, reply ) {
    this.RequestQueue.push( this._Get( data.uri, data.opts, reply ) );
  }

  async execute() {
    while( this.RequestQueue.length > 0 ) {
      var current = this.RequestQueue.shift();
      await current();
      await Utils.Sleep(5000); //promise that resolves after 5 seconds
    }
  }
}

由于 ES6 Promise 的性质,它们在构造时开始执行,因此 onRequest 事件内部的 this._Get() 返回一个已经在执行的 Promise。有没有一种干净的方法可以避免这种情况,以便我可以正确地将请求排队以备后用?

【问题讨论】:

  • 你可以改为限速对吧?

标签: javascript node.js promise es6-promise


【解决方案1】:

尝试将请求元数据添加到队列而不是实际请求 Promise:

onRequest(data, reply) {
    this.RequestQueue.push({ 
        uri: data.uri, 
        opts: data.opts, 
        reply: reply 
    });
}

async execute() {
    while(this.RequestQueue.length > 0) {
        var current = this.RequestQueue.shift();
        await this._Get(current.uri, current.opts, current.reply);
    }
}

【讨论】:

  • 因为没有看到如此简单的解决方案而自责。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2016-11-20
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多