我很努力與JavaScript異步模式,以達到這個目標:Javascript類屬性在構造函數中加載異步?
我有一個類(我使用CoffeeScript)與一些屬性在構造函數中從一些異步調用初始化。然後我有一些方法需要這些屬性才能工作。這裏是什麼,我試圖做一個簡單的例子:
# Class definition
class window.MyClass
constructor: ->
@attr = ... # loaded with an ajax call or whatever
myMethod: ->
console.log @attr
# User code
c = new MyClass()
c.myMethod() # should console.log the value loaded asynchronously
那麼問題將是,當myMethod()
被調用時,異步調用尚未完成。
我知道一些解決方案,但它們暗示將方法調用移入回調(或帶有promise的then函數)中。我想避免這個能夠從點擊處理程序或其他完全不相關的東西中調用此方法。
另請注意,我無法在我的方法內移動異步調用,因爲我可能會使用該屬性的幾種方法,並且我不想在每次調用時加載attr
,但只在構造函數中加載。
有什麼想法?