Created
July 19, 2021 11:26
-
-
Save Lcfvs/f81834d3f426cfb77db239f98d1cf28f to your computer and use it in GitHub Desktop.
Late dependencies
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
export default new Proxy(new Map(), { | |
get: (target, name) => { | |
if (!target.has(name)) { | |
target.set(name, [[]]) | |
} | |
const entry = target.get(name) | |
const [resolvers, value] = entry | |
return entry.length === 2 | |
? Promise.resolve(value) | |
: new Promise(resolve => resolvers.push(resolve)) | |
}, | |
set: (target, name, value) => { | |
if (!target.has(name)) { | |
target.set(name, [[]]) | |
} | |
const entry = target.get(name) ?? [[]] | |
const [resolvers] = entry | |
if (entry.length === 2) { | |
throw new Error(`Unable to redefine dependency: ${name}`) | |
} | |
entry.push(value) | |
for (const resolve of resolvers) { | |
resolve(value) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment