0

Why is obj[i] undefined inside .then()?

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 right value
    this.commentService.getAllComments(obj[i].id).then((res) => {
        ...
        console.log(obj[i]) // undefined ???
    })
}

Is there any posibility I can solve this situation and is it there an explanation why is undefined? Thank you for your time!

EDIT: The problem was that I was using var instead of let. Thank you!

Tenzolinho
  • 922
  • 2
  • 15
  • 35

1 Answers1

0

Using var will define variable on the wrapping function level. Since your code inside promise then callback is running after the for loop finished execution, you'll always get the i === obj.length. To avoid this, you can define block scope local variable, using let keyword.

for (let i = 0; i < obj.length; i++) { // let instead of var
    console.log(obj[i]) // has the right value
    this.commentService.getAllComments(obj[i].id).then((res) => {
        ...
        console.log(obj[i]) // has the right value
    })
}
Vadim
  • 8,701
  • 4
  • 43
  • 50
Tenzolinho
  • 922
  • 2
  • 15
  • 35