Galileo123 Galileo123 - 1 month ago 6
Javascript Question

Java script then chaining loses context of this

I am jumbled up with the .then chaining in Java script. Trying to figure out couldn't solve the below problem.

What I am trying to achieve is:
I have two arrays this.arrayA and this.arrayB and functionA and funcitonB populates them respectively and then I want to use those two array in funcitonC.

return functionA(this) //returns promise resolve , populates this.arrayA
.then(functionB(this)) //returns promise resolve , populates this.arrayB
.then(functionC(this)) //returns promise rejected if condition=true else resolves promise


I am trying to pass "this" context by assigning it as below but I always looses the reference and in functionB I always get output of functionA.I have tried the below code but it doesn't work.

var self = this;
return functionA(this) //returns promise resolve , populates this.arrayA
.then(functionB.bind(self)) //returns promise resolve , populates this.arrayB
.then(functionC.bind(self)) //returns promise rejected if condition=true else resolves promise

var _ = require('loadash');
functionA(that){
return new Promise(function(resolve, reject) {
resolve(
_.each(that.items1, function(item1){
var someStruct = {
name: item1.name,
type: item1.type
}
that.arrayA.push(someStruct);
}
)
});
}

functionB(that){
return new Promise(function(resolve, reject) {
resolve(
_.each(that.items2, function(item2){
var someStruct = {
name: item2.name,
type: item2.type
}
that.arrayB.push(someStruct);
}
)
});
}

functionC(that){
return new Promise(function(resolve, reject){
_.each(that.arrayA, function(someItems){
_.find(that.arrayB , function(someMoreItems){
if (someItem.name === someMoreItems.name && someItem.type != someMoreItems.type){
reject(Error("it's broken"))
}else{
resolve()
}
});
});
});
}


Can you please educate me so I can solve this problem?

thanks

Answer

store context this to a variable and use that variable every time.

Comments