簡體   English   中英

在類中的承諾內回調?

[英]Callback within a promise within a class?

我有一個類用於通過XMLHttpRequest(這是用於WebGL)加載外部資源,所以我正在加載模型,着色器等。我的計划是在完成所有這些請求時放入加載顯示,然后當它最終完成我希望它從創建它的原始函數運行回調函數。 但是,當我嘗試運行該回調時,我得到了奇怪的結果(例如,它無法訪問類中的任何加載的對象)。

我可以通過將“this”傳遞給加載類然后執行來解決這個問題

self = this; 
promise(self.callback());

但我更願意在完成加載后指定我希望它回調的函數。 有誰知道這是否可以做到? 我的代碼看起來像這樣:

主類

this.loadingClass = new LoadingClass(this.LoadingComplete, resources);

Main.prototype.LoadingComplete = function()
{
    // Returns undefined if i specify the callback function instead of just "this"
    console.log(this.loadingClass.anyOfTheMembersOfThisClass);
}

裝載班級

LoadingClass = function(callback, resources) {

  ..

        Promise.all(resources).then(function(loadedResources)
        {
            ..
            callback();

        });
}

當您傳遞函數對象時

(this.LoadingComplete, resources)

它被綁定的對象將不會被傳遞。 因此,只有函數對象LoadingComplete傳遞給LoadingClass並且當它被調用為

callback()

this值將是undefined (在嚴格模式下)。

要解決這個問題,

  • 你需要綁定this對象,就像這樣

     new LoadingClass(this.LoadingComplete.bind(this), resources) 
  • 如果您的環境支持ES2015的Arrow功能

     new LoadingClass(() => this.LoadingComplete(), resources); 

在這兩種情況下,當LoadingComplete從調用LoadingClass ,在this將被保留。

您正在從根對象中取消回調(讀取“this” )函數,因此它當然會丟失上下文。 使用Function.prototype.bind方法顯式指定bindingContext:

this.loadingClass = new LoadingClass(this.LoadingComplete.bind(this), resources);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM