Skip to content

Instantly share code, notes, and snippets.

@AoiYamada
Last active April 4, 2021 14:03
Show Gist options
  • Save AoiYamada/1f20e7139de3b3361acdaa07acf62338 to your computer and use it in GitHub Desktop.
Save AoiYamada/1f20e7139de3b3361acdaa07acf62338 to your computer and use it in GitHub Desktop.
const DataLoader = require("dataloader");
const stories = new Map([
[1, { id: 1, title: "story 1" }],
[2, { id: 2, title: "story 2" }],
[3, { id: 3, title: "story 3" }],
[4, { id: 4, title: "story 4" }],
[5, { id: 5, title: "story 5" }],
]);
const batchLoadFn = async (ids) => ids.map((id) => stories.get(id));
const loader = new DataLoader(batchLoadFn);
Promise.all([
loader.load(1),
loader.load(2),
loader.load(3),
loader.load(1),
loader.load(4),
]).then((results) => {
// batchLoadFn has only been called once
console.log(results);
// [
// { id: 1, title: 'story 1' },
// { id: 2, title: 'story 2' },
// { id: 3, title: 'story 3' },
// { id: 1, title: 'story 1' },
// { id: 4, title: 'story 4' }
// ]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment