【问题标题】:How can this wait until the update is finished to move to the next item?这怎么能等到更新完成才能移动到下一个项目?
【发布时间】:2017-01-19 10:05:11
【问题描述】:

我希望它等到 .update() 完成后再转到 otherPlayers 数组中的下一个玩家。我不知道发电机或其他东西是否可以在这里工作。

let {players} = this.props;

for(let player of otherPlayers) {
  const index = players.findIndex(p => p.Id === player.Id);
  const firebaseId = index && players[index].firebaseId;

  if(index !== -1 && firebaseId !== null) {
    window.firebase.database().ref(`/players/${firebaseId}`)
     .update({...player}, /* Callback possible */);
  } 
}

【问题讨论】:

  • 我想你可以在here找到答案。
  • 你在代码中使用 ES6 和 babel,因为你可以使用 await 函数让更新等待完成。
  • 我确实使用 ES6 和 babel。

标签: javascript asynchronous firebase firebase-realtime-database generator


【解决方案1】:

可能是这样的。

let {players} = this.props;

let p = Promise.resolve(); // just really want a promise to start

for(let player of otherPlayers) {
  const index = players.findIndex(p => p.Id === player.Id);
  const firebaseId = index && players[index].firebaseId;

  if(index !== -1 && firebaseId !== null) {
    p = p.then(()=>{
      return window.firebase.database().ref(`/players/${firebaseId}`)
       .update({...player}, /* Callback possible */);
    });
  } 
}

这从一个已解决的承诺开始,这将导致第一次更新立即执行。每个后续更新都链接到前一个承诺的解决方案。

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多