排队承诺(ES6)

w0f*_*w0f 2 javascript promise es6-promise

我正在编写一个从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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

max*_*paj 6

尝试将有关请求的信息而不是实际的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 踢自己,因为没有看到如此简单的解决方案。谢谢! (3认同)