gpt4 book ai didi

javascript - Nodejs 异步 promise 队列

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:47 24 4
gpt4 key购买 nike

我需要使用速率受限的 API。例如,我在一秒钟内只能进行 10 次 API 调用,因此我需要等待当前秒结束才能进行另一次 API 调用。

为此,我想制作一个可以自行管理的异步队列。它的主要功能是让我向队列添加一个新的 promise ,当 promise 被解决时,应用程序会收到通知:

let queue = new Queue()

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

我如何使用普通的 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
}

}

最佳答案

在当前的实现中,当添加到队列时,api.get() 将被立即调用。您应该添加路径(或者api.get路径)并让 AsyncQueue 在可以时初始化 Promise。确保让 add 返回一个在 API 调用完成后解析的 Promise。

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

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');
});

关于javascript - Nodejs 异步 promise 队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com