javascript - 具有异步初始化的单例

标签 javascript promise singleton

我有一个用例,其中 Singleton 对象有一个异步步骤作为其初始化的一部分。此单例的其他公共(public)方法取决于初始化步骤设置的实例变量。我将如何使异步调用同步?

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

关于javascript - 具有异步初始化的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553201/

相关文章:

javascript - 返回由链式 JavaScript Promise 创建的对象

java - 正确使用 Singleton getInstance 方法

javascript - 如何在我的 Web View Android 应用程序中使用 Polymer 项目

javascript - 这是对 eval() 的错误使用吗

javascript - 使用 Lodash 省略嵌套属性

java - 单例类如何使用接口(interface)?

c++ - 多个 QApplication 实例

javascript - 使用可选值过滤集合

javascript - 来自 C 代码的异步 javascript 库调用完成得太晚

javascript - 为什么 'new Promise(...)' 返回 'undefined' ?