我有一个使用场景,其中一个Singleton对象在其初始化过程中包含异步步骤。此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();