繁体   English   中英

具有异步初始化的Singleton

[英]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创建某种类似单例的方法,则仍然必须对异步调用使用promise或回调,并对其进行处理,而不是尝试将异步转换为同步

就像是

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
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM