简体   繁体   English

在类中的承诺内回调?

[英]Callback within a promise within a class?

I have a class that I use to load external resources via an XMLHttpRequest (this is for WebGL) so I'm loading models, shaders etc. My plan was to put a loading display up whilst it did all these requests and then when it's finally complete I want it to run a callback function from the original function that created it. 我有一个类用于通过XMLHttpRequest(这是用于WebGL)加载外部资源,所以我正在加载模型,着色器等。我的计划是在完成所有这些请求时放入加载显示,然后当它最终完成我希望它从创建它的原始函数运行回调函数。 However, I'm getting strange results when I try to run that call back (such as it has no access of any of the objects within the class that did the loading). 但是,当我尝试运行该回调时,我得到了奇怪的结果(例如,它无法访问类中的任何加载的对象)。

I can get around this problem by passing "this" into the loading class and then doing 我可以通过将“this”传递给加载类然后执行来解决这个问题

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

but I'd much rather specify the function that I want it to callback to after its done the loading. 但我更愿意在完成加载后指定我希望它回调的函数。 Does anyone know if this can be done? 有谁知道这是否可以做到? My code looks like this: 我的代码看起来像这样:

Main Class 主类

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

Loading Class 装载班级

LoadingClass = function(callback, resources) {

  ..

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

        });
}

When you pass the function object as 当您传递函数对象时

(this.LoadingComplete, resources)

the object to which it was bound, will not be passed. 它被绑定的对象将不会被传递。 So, only the function object LoadingComplete is passed to LoadingClass and when it is invoked as 因此,只有函数对象LoadingComplete传递给LoadingClass并且当它被调用为

callback()

the this value will be undefined (in strict mode). this值将是undefined (在严格模式下)。

To fix this, 要解决这个问题,

  • you need to bind the this object, like this 你需要绑定this对象,就像这样

     new LoadingClass(this.LoadingComplete.bind(this), resources) 
  • if your environment supports ES2015's Arrow functions 如果您的环境支持ES2015的Arrow功能

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

In both these cases, when the LoadingComplete is invoked from LoadingClass , the this will be retained. 在这两种情况下,当LoadingComplete从调用LoadingClass ,在this将被保留。

You are detouching callback (read about "this" ) function from the root object, so of course it loses context. 您正在从根对象中取消回调(读取“this” )函数,因此它当然会丢失上下文。 Specify bindingContext explicitly with Function.prototype.bind method: 使用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