factory.dataPromise = null;
factory.getData = function() {
if (this.dataPromise !== null) {
return this.dataPromise;
}
else {
const req = {...};
return this.dataPromise = $http(req).then((res) => {
this.data1 = res.data.response[0];
this.data2 = res.data.response[1];
return res;
})
}
}
This answer may be a bit simplistic, but it should suffice for now. However, I recommend refactoring the code for better efficiency. Nevertheless, I tried to keep the changes minimal.
The crucial point is always returning a promise. By ensuring that, everything should work smoothly. If we verify that this.data1
and this.data2
already exist, we can return a resolved promise immediately without making an additional HTTP request.
Just a reminder, include $q
(or any other Promise library of your choice) to create promises easily.
To Consider: It's not a major issue, but when you invoke factory.getData()
, you're not actually utilizing the resolved value from the promise. Hence, in my answer, I simply have a placeholder variable called whateverdata
, as the returned value based on your code is irrelevant since it's not being used.
In this scenario, it might be better to let the promise handle the task. In light of this, I propose the following refactor:
factory.dataPromise = null;
factory.getData = function() {
if (this.dataPromise !== null) {
return this.dataPromise;
}
else {
const req = {...};
return this.dataPromise = $http(req).then((res) => {
this.data1 = res.data.response[0];
this.data2 = res.data.response[1];
return { data1: this.data1, data2: this.data2 };
})
}
}
this.factory.getData().then((data) => {
this.controllerData1 = data.data1;
this.controllerData2 = data.data2;
})
This approach is more intuitive and effectively capitalizes on the advantages of promises. Ultimately, the decision rests with you.