Skip to content

Instantly share code, notes, and snippets.

@AoiYamada
Last active April 5, 2021 07:24
Show Gist options
  • Save AoiYamada/4d91cbc7aa3787a70ef4b9ecbdfc7027 to your computer and use it in GitHub Desktop.
Save AoiYamada/4d91cbc7aa3787a70ef4b9ecbdfc7027 to your computer and use it in GitHub Desktop.
const DataLoader = require("dataloader");
const users = new Map([
[1, { id: 1, name: "Tom" }],
[2, { id: 2, name: "John" }],
[3, { id: 3, name: "Ann" }],
[4, { id: 4, name: "Peter" }],
[5, { id: 5, name: "May" }],
]);
const batchLoadFn = async (ids) => ids.map((id) => users.get(id));
const loader = new DataLoader(batchLoadFn);
Promise.all([
// Loaded 3 authors from the original comment list
loader.load(1),
loader.load(2),
loader.load(3),
])
.then((results) => {
// batchLoadFn has only been called once here
console.log(results);
// [
// { id: 1, name: 'Tom' },
// { id: 2, name: 'John' },
// { id: 3, name: 'Ann' }
// ]
})
.then(() => {
return Promise.all([
// Load additional authors who were loaded before when open sub-comments
loader.load(1),
loader.load(2),
]);
})
.then((results) => {
// Resolve directly without calling batchLoadFn
console.log(results);
// [
// { id: 1, name: 'Tom' },
// { id: 2, name: 'John' }
// ]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment