Last active
May 16, 2020 21:46
-
-
Save jprivillaso/bb06a10fece660fa8a884ef676a03397 to your computer and use it in GitHub Desktop.
WeakMap Usage
This file contains 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 getSomeUserFromAPI = async () => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve({ | |
id: 1, | |
name: 'Juan', | |
state: 'ACTIVE' | |
}); | |
}, 100); | |
}); | |
}; | |
const map = new WeakMap(); | |
// map.set(1, 1); // Triggers an error. Keys must be objects | |
(async () => { | |
const user = await getSomeUserFromAPI(); | |
map.set(user, user.state); | |
console.log(map); // If you run it using node: WeakMap { <items unknown> } | |
/** | |
* If you run it in the browser: WeakMap {{…} => "ACTIVE"}. | |
* The console uses the debugging API of the JS engine, | |
* which allows access to the internals of objects | |
* (also to promise states, wrapped primitives, etc.) and many more. | |
* | |
* https://stackoverflow.com/a/32543187/2599811 | |
*/ | |
console.log(map); | |
// for (let i of map) {} // Uncaught TypeError: map is not iterable | |
console.log(map.get(user)); // ACTIVE | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment