I'm writing a Javascript class with a send
method which gets a promise from other class members and resolves it. The success and error functions passed to it are members of the class. It is not working as expected. The method code:
Request.prototype.send = function () {
if (!this.promise) {
this.promise = this.api[this.method](this.flatArgsArray, this.options);
this.promise.then(this.distributeResults, this.distributeErrors);
} else {
throw new Error('This request was already answered');
}
}
The distributeResults
method fails, and the code is:
Request.prototype.distributeResults = function (result) {
if (this.isEntityRequest) {
var items = result.body[array_names[this.method]];
items.forEach(this.distributeEntities);
} else {
this.callbacks.forEach(function (cb) {
cb(null, result);
});
}
}
It fails on the this.callbacks.forEach
line saying this.callbacks
is undefined. But the this.isEntityRequest
had to be true so I debugged and found out that everything starting with this.
was undefined.
So in the send
method, when I pass the methods to the promise's then
, I binded the distributeResults
method like this.distributeResults.bind(this)
and it worked. But I'm feeling it redundant. If I have to do that I'd rather define the method as a regular JS function. I thought defining it as a method of the class would save me the binding.
So, if I defined the promise response as a class method, why do I still need to bind it? What about binding am I missing?