Promise.race & Promise.all 導致'this'失去



我有一个带有构造函数和几个方法的jsnode类c,我通过var example=new c(参数)创建了一个对象;

其中一个方法需要访问对象属性,我使用它来做到这一点。该方法具有以下代码的功能:

this.Busy=true;
console.log(this);   // outputs all the information of the object    
Promise.race([Promise.all(
    [asynchronousFunction("user1"),asynchronousFunction("user2"),asynchronousFunction("user3")],
        TimeoutFunction()])
    .then((output)=>{console.log(this);} // this is defined with all information here

异步函数看起来像这样:

var asynchronousFunction= function(userToQuery) {
    console.log(this);  // undefined
    if(this.Busy===false) {
        return New Promise((resolve,reject) => {
            this.Busy=true;
            /* (this code uses promises; it checks the last time an object in the array (this.table) was updated, contacts the server asynchronously, updates the array and returns the result) */
        }
    }
}

我必须检查数组this.table的原因是因为服务器过载;它只应该根据已经获取的数据的时间戳进行查询。如何确保异步函数可以修改对象的 this?我尝试过绑定、调用和箭头函数,但没有结果。我变得绝望了。

你可以

var self = this;,然后将this更改为self

var self = this;
//...
self.Busy=true;
//...
var asynchronousFunction= function(userToQuery) {
    console.log(self);  // undefined
    if(self.Busy===false) {
        return New Promise((resolve,reject) => {
            self.Busy=true;
        }
    }
} 

我找到了解决方案:Promise.race([Promise.all( [asyncFunction("user1").bind(this),asyncFunction("user2").bind(this),asyncFunction("user3").绑定(这)], 超时函数()])

Bind(this) 只将 this 应用于第一个函数。

最新更新