Nodejs Async Promise Queue

时间:2018-05-23 23:05:12

标签: javascript node.js asynchronous queue es6-promise

I need to consume a rate limited API. For example, I can only make 10 API calls in a second, so I will need to wait the end of the current second to make another API call.

To achieve this, I want to make an asynchronous queue that can manage this on its own. The main functionality of it is to let me add a new promise to the queue, and when the promise is resolved the application is notified:

let queue = new Queue()

queue.add(api.get('/somepath')).then(res => { // handle response });

How can I implement this using ordinary Promises?

export class AsyncQueue {

    private queue: Array<Promise<any>>;


    add(promise, fct) {
        this.queue.push(promise);
    }

    resolveNext() {
        this.queue.pop().then({
            // how to resolve the waiting promise in my application
        })
    }

    get length() {
        return this.queue.length
    }

}

1 个答案:

答案 0 :(得分:4)

使用当前的实现,当api.get()到队列时,add将立即被称为 。您应该add 路径(或者可能是api.getpath),并AsyncQueue初始化承诺<\ n>能够。确保add返回一个在API调用完成后解析的Promise。

例如,在vanilla JS中,它看起来像这样:

&#13;
&#13;
const apiGet = () => new Promise(resolve => setTimeout(resolve, 1000));

class AsyncQueue {
  queue = [];
  constructor() {
    setInterval(this.resolveNext.bind(this), 2000);
  }
  add(fn, param) {
    return new Promise(resolve => {
      this.queue.unshift({ fn, param, resolve });
    });
  }
  resolveNext() {
    if (!this.queue.length) return;
    const { fn, param, resolve } = this.queue.pop();
    fn(param).then(resolve);
  }
}


const queue = new AsyncQueue()
console.log('start');
// Will resolve after 2000 + 1000 seconds:
queue.add(apiGet, '/somepath').then(res => {
  console.log('handling response 1');
});
// Will resolve after 4000 + 1000 seconds:
queue.add(apiGet, '/somepath').then(res => {
  console.log('handling response 2');
});
&#13;
&#13;
&#13;