排队承诺(ES6)

时间:2018-06-19 16:08:30

标签: javascript promise es6-promise

我正在编写一个NodeJS服务,该服务从API请求数据。在负载下,我不想对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承诺的性质,它们在构造后便开始执行,因此this._Get()事件内部的onRequest返回已执行的承诺。有没有一种干净的方法来避免这种情况,以便我可以将请求正确地排队以便以后使用?

1 个答案:

答案 0 :(得分:4)

尝试将有关请求的信息添加到队列中,而不是实际的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);
    }
}