具有异步初始化的单例模式
Singleton with async initialization
我有一个用例,其中一个Singleton对象具有异步步骤作为其初始化的一部分。此单例的其他公共方法依赖于初始化步骤设置的实例变量。我该如何让异步调用同步呢?
var mySingleton = (function () {
var instance;
function init() {
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateAsync = (function(){
// async call which returns an object
})();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getPrivateValue: function() {
return privateAsync;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
var foo = mySingleton.getInstance().getPrivateValue();
如果你真的想使用IIFE来创建一个类似于单例的方法,你仍然必须在异步调用中使用承诺或回调,并且使用它们,而不是尝试将异步转换为同步
之类的var mySingleton = (function() {
var instance;
function init() {
// Private methods and variables
function privateMethod() {
console.log("I am private");
}
var privateAsync = new Promise(function(resolve, reject) {
// async call which returns an object
// resolve or reject based on result of async call here
});
return {
// Public methods and variables
publicMethod: function() {
console.log("The public can see me!");
},
publicProperty: "I am also public",
getPrivateValue: function() {
return privateAsync;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
var foo = mySingleton.getInstance().getPrivateValue().then(function(result) {
// woohoo
}).catch(function(err) {
// epic fail
})
相关文章:
- javascript严格模式下oop函数的全局初始化
- 如何初始化Twitter引导程序表单助手日期选择器
- 如何在第一次点击时突出显示链接;并在第二次单击时跟随它,除非在其他地方单击,然后重新初始化未高亮显示的状态
- jQuery - 用户单击模式上的“是”按钮后返回到初始屏幕
- AngularJS 模式单例在服务中未更新视图
- 角度$scope变量未显示在引导模式初始化上
- MVC / 引导 - 组中的单选按钮在初始化时未选择
- Javascript 单例模式
- 在单例模式中引用变量的根父级
- Javascript 文字对象和单例模式
- node.jssocket.io定时器-单例模式
- 使用单例模式维护整个应用中的数组状态
- 用于特殊单例模式的JSDoc
- 在javascript中还有其他实现单例模式的方法吗?
- JavaScript单例模式-差异
- 在Typescript/ES6中,单例模式的正确方式是什么?
- 如何保存javascript "this"单例模式中的上下文
- 下面这个单例模式有什么问题吗?
- 具有异步初始化的单例模式
- 用这种方式实现Javascript单例模式有什么问题吗?