Skip to content

Instantly share code, notes, and snippets.

@ranyefet
Created April 2, 2019 17:28
Show Gist options
  • Save ranyefet/6a439b25fe01e0d71c09ea5001f70cee to your computer and use it in GitHub Desktop.
Save ranyefet/6a439b25fe01e0d71c09ea5001f70cee to your computer and use it in GitHub Desktop.
async function getManyUsers(ids) {
console.log("getManyUsers", ids);
return ids.map(id => ({ id, name: "name " + id }));
}
function arrayToMap(arr) {
const map = new Map();
arr.forEach(result => {
map.set(result.id, result);
});
return map;
}
function throttleGetManyFn(fn, throttle) {
let count = 0;
return new Promise((resolve, reject) => {});
}
function createLoader(getMany, opts) {
let queue = [];
let flushesCount = 0;
const { throttle } = opts || {};
async function flush() {
if (!queue.length) return;
console.log("Flush", queue);
const oldQueue = queue;
queue = [];
const ids = oldQueue.map(({ id }) => id);
const uniqueIds = Array.from(new Set(ids));
const results = await getMany(uniqueIds);
const resultsMap = arrayToMap(results);
return oldQueue.map(({ id, resolve, reject }) => {
const result = resultsMap.get(id);
resolve(result);
});
}
setInterval(flush, 1000); // configurable
return function getOne(id) {
return new Promise(async (resolve, reject) => {
queue.push({ id, resolve, reject });
});
};
}
(async function main() {
const getOneUser = createLoader(getManyUsers);
const promises = [getOneUser(1), getOneUser(2), getOneUser(3)];
console.log("Got", await Promise.all(promises));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment