javascript 如何将常规函数转换为来自单例模式的异步/等待函数?

hec6srdp  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(112)

我从dofactory.com复制了以下设计模式。我的问题是如何将其转换为async/await?

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    console.log("Same instance? " + (instance1 === instance2));
}
qgelzfjb

qgelzfjb1#

它可能是这样的(如果没有异步创建示例的代码,很难判断):

const Singleton = (() => {
    let instance;

    const createInstance = async () => {
        // no need to `await` in here unless it's actually needed as part of
        // your singleton build process; return the object or the promise,
        // whichever you end up with.
        const object = new Object("I am the instance");

        return object;
    }

    return {
        getInstance: async () => {
            if(!instance) {
                // `createInstance()` always returns a promise because
                // it's async; store the promise; this only happens 
                // in the first call to `getInstance()`
                instance = createInstance();
            }

            // it doesn't matter that we're returning the promise
            // (resolved or not), chained promises are coalesced 
            // and the `await`s in `run()` will either wait for 
            // resolution or resolve immediately
            return instance;
        }
    };
})();

const run = async () => {
    // let instance1 = await Singleton.getInstance();
    // let instance2 = await Singleton.getInstance();
    // not a good way to test this, lets try something else

    let [instance1, instance2] = await Promise.all([
        Singleton.getInstance(),
        Singleton.getInstance(),
    ]);

    console.log("instance1:", instance1.toString());
    console.log("instance2:", instance2.toString());
    console.log("Same instance?", (instance1 === instance2));
};

run();

相关问题