具有异步初始化的单例模式

Singleton with async initialization

本文关键字:单例模式 初始化 异步      更新时间:2023-09-26

我有一个用例,其中一个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
})