When I am loading data for multiple users and intending to store it in a JavaScript array, the process can get tricky due to limitations with TypeScript. Here is an example of my struggle:
for(var i = 0; i < 5; i++) {
promise[i] = httpquery.then(
(data) => { this.usersData[i] = data }
);
)
...
this.$q.all[promise].then(......
Unfortunately, due to restrictions within TypeScript, the lambda expression only protects 'this' and not the variable 'i'. This means that in my case, the data will always be stored in this.usersData[5]
.
I realized that I need a closure to address this issue, as lambda expressions in TypeScript act similarly to closures in some ways.
Let's attempt to work around this problem using TypeScript:
for(var i = 0; i < 5; i++) {
promise[i] = (index = i) => {
return httpquery.then(
(data) => { this.usersData[index] = data }
);
}();
)
However, this approach does not work at all and doesn't even compile. The reason being that () => {}
is not recognized as a function. To resolve this, I had to adjust my code like so:
for(var i = 0; i < 5; i++) {
var getData = (index = i) => {
return httpquery.then(
(data) => { this.usersData[index] = data }
);
};
promise[i] = getData();
)
This solution felt less elegant than I would have liked. So my question remains: is there a more graceful way to handle such issues in TypeScript? Should I continue using the lambda expressions in this manner? And why does
() => {}()
not work, while
var test = () => {};
test();
does the job just fine? Could it be due to TypeScript's compiler not fully understanding that the lambda should be treated as a function?
Thank you for any insights or suggestions.