0

我想使用带有异步函数的 JavaScript 中的 Multiton 模式来缓存性能密集型对象生成。我提供了一个例子,想知道我是否正确地实现了它,即这是否足以保证同名的对象永远不会生成两次,无论执行的异步顺序如何。

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>

4

0 回答 0