简体   繁体   English

无法设置undefined里面的属性'comment'.then()

[英]Cannot set property 'comment' of undefined inside .then()

Why is obj[i] undefined inside .then() ? 为什么obj[i].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 . 编辑:问题是我使用var而不是let Thank you! 谢谢!

Using var will define variable on the wrapping function level. 使用var将在包装函数级别定义变量。 Since your code inside promise then callback is running after the for loop finished execution, you'll always get the i === obj.length . 由于你的代码在promise中,然后在for循环完成执行后运行回调,你总是得到i === obj.length To avoid this, you can define block scope local variable, using let keyword. 为避免这种情况,您可以使用let关键字定义块范围局部变量。

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
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM