【问题标题】:Firestore Reference Key (AutoID) is behaving wierd inside FOR loopFirestore 参考密钥(AutoID)在 FOR 循环中表现得很奇怪
【发布时间】:2018-08-08 08:14:16
【问题描述】:

这是一个jsfiddle,它复制了这个问题。我为此使用了一个测试数据库,所以不用担心数据使用不当。

我的数据是这样的:

slides{
  42rJA379fssKUe11KuCB{
    slideTitle: "Sample Title 4"
  }
  Sp4611QJwQ9GrE2nLauZ{
    slideTitle: "Sample Title 3"
  }
  VfwrwjNFitutSUUzmViE{
    slideTitle: "Sample Title 1"
  }
  W6y1aQKJRxTRV2Jnwd2q{
    slideTitle: "Sample Title 2"
  }
}

我使用的代码是这样的:

slideArray = ["42rJA379fssKUe11KuCB", "Sp4611QJwQ9GrE2nLauZ", "VfwrwjNFitutSUUzmViE", "W6y1aQKJRxTRV2Jnwd2q"];

for(var i = 0; i < slideArray.length; i++){
  slideKey = slideArray[i];
  console.log('Outside the slide key is:' + slideKey);
  db.collection('slides').doc(slideKey).get().then(function(snap){
    console.log('Inside the slide key is' + slideKey);
    console.log('The slides Title prints correctly however: ' + snap.data().slideTitle);
  })
}

我得到的输出是这样的:

Outside the slide key is: Sp4611QJwQ9GrE2nLauZ
Outside the slide key is: VfwrwjNFitutSUUzmViE
Outside the slide key is: W6y1aQKJRxTRV2Jnwd2q
Inside the slide key is W6y1aQKJRxTRV2Jnwd2q
The slides Title prints correctly however: Sample Title 4
Inside the slide key is W6y1aQKJRxTRV2Jnwd2q
The slides Title prints correctly however: Sample Title 3
Inside the slide key is W6y1aQKJRxTRV2Jnwd2q
The slides Title prints correctly however: Sample Title 1
Inside the slide key is W6y1aQKJRxTRV2Jnwd2q
The slides Title prints correctly however: Sample Title 2

我期望它做什么:

如您所见,它正在打印正确的示例标题。这意味着它获取每个循环的数据。但是里面的 slideKey 始终是数组中的最后一个 Key。我希望函数内的 slideKey 是当前的。我怎样才能做到这一点?

同样在循环外,第一个键不显示?有人可以解释我做错了什么吗?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    循环的每次迭代都会生成一个 Promise(通过 .get()),该 Promise 在 JavaScript 事件循环的后续迭代中被解析和使用(.then(...))。 到那时您的回调被调用,slideKey 将始终等于循环中的最后一个元素。

    您可以使用slideArray.forEach(function(slideKey) {...}) 轻松修复它。循环的每次调用都将在一个新的函数范围内发生,因此每次调用都会看到一个不同的slideKey 变量。

    如果你的目标环境足够新,你也可以像这样使用 ES5 箭头函数:slideArray.forEach(slideKey =&gt; { ... })

    【讨论】:

    • 啊!感谢您的解释和解决方案。这对我有用:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多