Asynchronous Multiton pattern in JavaScript?

134 Views Asked by At

I want to cache performance intensive object generation using the Multiton pattern in JavaScript with an asynchronous function. I provide an example and would like to know if I implemented that correctly, i.e. whether that is enough to guarantee that an object with the same name will never be generated twice, no matter the asynchronous order of execution.

const things = new Map();

// in real life, fetch from network or other asynchronous, slow operation
async function slowFunc() {
    return Math.floor(Math.random() * Math.floor(100));
}

class Thing {
    constructor(n) {
        this.n = n;
    }

    static async get(name) {
        let thing = things.get(name);
        if (thing) {
            console.log("Reusing existing", name, "with n=", (await thing).n);
            return thing;
        }
        const promise = slowFunc().then(n => {
            thing = new Thing(n);
            console.log("Creating new", name, "with n=", n);
            return thing;
        }, );
        things.set(name, promise);
        return promise;
    }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <button onclick="Thing.get('a');">Make an A</button>
  <button onclick="Thing.get('b');">Make a B</button>
</body>
</html>

0

There are 0 best solutions below