I have a use case where a Singleton object has an asynchronous step as part of its initialization. Other public methods of this singleton depend on an instance variable that the initialization step sets up. How would I go about making an async call synchronous?
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();
If you really want to use an IIFE to create a somewhat singleton-like approach, you still have to use promises or callbacks with async calls, and work with them, not try to convert asynchronous to synchronous
Something like
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With