Created
November 14, 2019 18:13
-
-
Save yuradmt/89245c85bd31cb7c04729c8bb7106493 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 getManyUsers = async (ids) => { | |
const USERS = { | |
1: { name: "foo" }, | |
2: { name: "bar" } | |
}; | |
return ids.map(id => USERS[id] || null); | |
} | |
function createLoader(getMany) { | |
return async function (key) { | |
const res = await getMany([key]); | |
return res[0]; | |
}; | |
} | |
function createLoader2(getMany) { | |
const buf = []; | |
return function (key) { | |
return new Promise((resolve, reject) => { | |
buf.push(key); | |
process.nextTick(() => { | |
const many = await getMany(buf); | |
resolve(many[key]); | |
}) | |
}); | |
}; | |
const getOneUser = createLoader2(getManyUsers); | |
(async function main() { | |
console.log(await getOneUser(1)); | |
console.log(await getOneUser(4)); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment