我想使用JavaScript中具有异步功能的Multiton模式来缓存性能密集型对象的生成。我提供了一个示例,想知道我是否正确实现了该示例,即是否足以保证同名对象无论异步执行顺序都不会生成两次。
CREATE OR REPLACE FUNCTION vat_total_sum() RETURNS TRIGGER AS $$
BEGIN
UPDATE goods SET vat_total_sum = NEW.vat_sum / 100 * NEW.vat_percent
WHERE goods_id = new.goods_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER vat_total_sum AFTER INSERT OR UPDATE ON goods
FOR EACH ROW EXECUTE PROCEDURE vat_total_sum();
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;
}
}