Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with async initialization

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();
like image 623
johnborges Avatar asked Sep 18 '16 01:09

johnborges


1 Answers

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
})
like image 84
adeneo Avatar answered Oct 02 '22 10:10

adeneo