javascript
Batched Requests - AirTable - Automations - Front End - 12/3/21
/**
GET /read?keys=foo,bar
Response:
{
"foo": 12,
"bar": 42
}
Implement a function getKey(key) which fetches the specified key
and returns its value asynchronously to the caller.
The function signature is a starting point. Feel free to wrap it
in a class or add additional arguments if needed.
Desired behavior:
If getKey is called multiple times in a small window of time,
there should be a single network request to fetch all the required
values. For example, if the below 3 calls happen within a small window
of time, there should be a single network request:
getKey('foo', cb)
getKey('bar')
getKey('foo')
*/
const keys = new Set();
const keysToCallback = [];
let isFirstCall = true;
function getKey(key, callback: (data: number) => void) {
keys.add(key);
keysToCallback.push({
key, callback
});
//const keyPromise = new Promise();
if (isFirstCall) {
setTimeout(() => {
$.ajax({
path: '/read?keys=' + [...keys].join(',')
}).then((values) => {
//keyPromise.resolve(keysAndValues);
// Object.keys
keysToCallback.foreach((value) => {
[key, callback] = value
callback(values[key])
})
}, () => {
// Log
});
isFirstCall = true;
}, 1000);
isFirstCall = false;
}
// keyPromise.then((values) => {
// return values[key];
// });
}
Was this helpful?
Similar Posts