JSFiddle - React, Tailwind, and code Playground
JavaScript
class Api {
constructor(url, delay) {
this.url = `${url}?key=`;
this.delay = delay;
this.queue = [];
this.blocked = false;
}
getkey = (key, cb) => {
this.queue.push([key, cb]);
if (!this.blocked) {
this.blocked = true;
setTimeout(() => this.callApi(), this.delay);
}
};
callApi = async () => {
if (this.queue.length) {
const keyMap = {};
while (this.queue.length) {
const [key, cb] = this.queue.shift();
(keyMap[key] || (keyMap[key] = [])).push(cb);
}
try {
const response = await fetch(this.url + Object.keys(keyMap).join(','));
if (!response.ok) {
throw 'Status: ' + response.status;
}
const data = await response.json();
console.log(data)
/*
Testing for httpbin response.
const data = {
args: {
key: "foo"
}
};
*/
data[data.args.key] = 12;
for (const [key, val] of Object.entries(data)) {
(keyMap[key] || []).forEach(cb => cb(val));
}
} catch (error) {
throw error;
}
this.callApi();
} else {
this.blocked = false;
}
};
}
/* Test case */
const api = new Api('https://httpbin.org/get', 3000);
const test = (x) => console.log(x);
api.getkey('foo', test);