Last active
April 4, 2021 14:03
-
-
Save AoiYamada/1f20e7139de3b3361acdaa07acf62338 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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