在类中的承诺内回调?

时间:2016-03-22 07:36:26

标签: javascript callback promise

我有一个类用于通过XMLHttpRequest(这是用于WebGL)加载外部资源,所以我正在加载模型,着色器等。我的计划是在完成所有这些请求时加载显示然后当它最终完成时,我希望它从创建它的原始函数运行回调函数。但是,当我尝试运行该回调时,我得到了奇怪的结果(例如,它无法访问正在加载的类中的任何对象)。

我可以通过"这个"来解决这个问题。进入加载类然后执行

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();

        });
}

2 个答案:

答案 0 :(得分:2)

将函数对象作为

传递时
(this.LoadingComplete, resources)

它所绑定的对象将不会被传递。因此,只有函数对象LoadingComplete被传递给LoadingClass,并且当它被调用为

callback()

this值为undefined(严格模式下)。

要解决此问题,

  • 您需要绑定this对象,就像这样

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

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

在这两种情况下,当从LoadingComplete调用LoadingClass时,this将被保留。

答案 1 :(得分:1)

您正在从根对象中取消回调(读取"this")函数,因此它当然会丢失上下文。使用Function.prototype.bind方法显式指定bindingContext:

this.loadingClass = new LoadingClass(this.LoadingComplete.bind(this), resources);
相关问题