簡體   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