class RequestQueue {
constructor(maxPerMinute = 100) {
this.maxPerMinute = maxPerMinute;
this.queue = [];
this.processing = false;
}
async add(fn) {
return new Promise((resolve, reject) => {
this.queue.push({ fn, resolve, reject });
this.process();
});
}
async process() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
while (this.queue.length > 0) {
const { fn, resolve, reject } = this.queue.shift();
try {
const result = await fn();
resolve(result);
} catch (error) {
reject(error);
}
// Wait to stay within rate limit
const delay = (60 * 1000) / this.maxPerMinute;
await new Promise(r => setTimeout(r, delay));
}
this.processing = false;
}
}
// Usage
const queue = new RequestQueue(100);
async function createPayment(data) {
return queue.add(() =>
fetch('https://card2crypto.cc/api/v1/payments', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
);
}