gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:10:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com