Why does obj[i]
become undefined inside the .then()
function?
obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', 'age': '24', 'group': 'grA'}, {'id': 3, 'name': 'anne', 'age': '25', 'group': 'grB'}]
for (var i = 0; i < obj.length; i++) {
console.log(obj[i]) // has the correct value
this.commentService.getAllComments(obj[i].id).then((res) => {
...
console.log(obj[i]) // ends up being undefined ???
})
}
Any solutions to prevent obj[i]
from becoming undefined within the .then()
block? Can you explain why this happens? Appreciate your insights!
UPDATE: The issue was using var
instead of let
. Thank you for pointing that out!