如何将常规函数转换为async/await函数从单例模式?



我从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));
}

可能是这样的(如果没有异步创建实例的代码,很难分辨):

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();

最新更新