【发布时间】:2018-11-28 16:07:19
【问题描述】:
我正在编写一个从 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 Promise 的性质,它们在构造时开始执行,因此 onRequest 事件内部的 this._Get() 返回一个已经在执行的 Promise。有没有一种干净的方法可以避免这种情况,以便我可以正确地将请求排队以备后用?
【问题讨论】:
-
你可以改为限速对吧?
标签: javascript node.js promise es6-promise