I'm trying to solve exactly this problem but in ES2020.
Let's say I have a promise that resolves after one second, and several awaits for that promise, called concurrently from different places. The promise must settle only once, and the awaits should return its result. In the code below, I want all callers to get 1.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let counter = 0;
async function getSomething() {
await sleep(1000);
return ++counter;
}
(async function caller1() {
console.log(await getSomething());
})();
(async function caller2() {
console.log(await getSomething());
})();
(async function caller3() {
console.log(await getSomething());
})();
How can I do that?