繁体   English   中英

排队承诺(ES6)

[英]Queuing Promises (ES6)

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

尝试将请求元数据添加到队列而不是实际的请求 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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM