排队承诺(ES6)

问题描述 投票:1回答:1

我正在编写一个从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承诺的性质,它们在构造时开始执行,因此this._Get()事件中的onRequest返回已经执行的承诺。是否有一种干净的方法可以避免这种情况,以便我可以在以后正确排队请求?

javascript promise es6-promise
1个回答
5
投票

尝试将有关请求的信息添加到队列而不是实际的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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.