Skip to content

Instantly share code, notes, and snippets.

@hugozap
Last active March 4, 2021 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugozap/b7ccad62d86629dafa43fb16aff42583 to your computer and use it in GitHub Desktop.
Save hugozap/b7ccad62d86629dafa43fb16aff42583 to your computer and use it in GitHub Desktop.
/* Creates a data loader.
Accepts a batch function that should return a promise
that resolves with the list of values fetched for
each of the keys */
function createLoader(batch) {
const keys = []
const resolvers = []
//Here's the magic, accumulate calls and run them on the next tick
process.nextTick(async () => {
console.log('resolving batch for keys:', keys);
const values = await batch(keys);
//Resolver promesas en el orden
resolvers.forEach((res, ix) => {
res(values[ix])
});
});
return {
load(id) {
keys.push(id);
let resolver;
//Create a deferred promise and store the resolve callback in the "resolvers" array
return new Promise((resolve, reject) => {
resolver = resolve;
resolvers.push(resolver);
})
}
}
}
//Test loading from db
(async () => {
const getBatchRecordsForKeys = async (keys) => {
console.log('Just one DB call needed!')
//Real code would call a store procedure
//or create one query that returns all values for the keys
return keys.map(key => ({ id: key, name: "person " + key }))
}
const loader = createLoader(getBatchRecordsForKeys);
const p1 = loader.load(1);
const p2 = loader.load(2);
const p3 = loader.load(3);
const p4 = loader.load(4);
p1.then((value)=>{console.log(value)})
p2.then((value)=>{console.log(value)})
p3.then((value)=>{console.log(value)})
p4.then((value)=>{console.log(value)})
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment