javascript - 这怎么能等到更新完才移到下一项呢?

标签 javascript asynchronous firebase firebase-realtime-database generator

我希望它等到 .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 */);
  } 
}

最佳答案

可能是这样的。

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 */);
    });
  } 
}

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

关于javascript - 这怎么能等到更新完才移到下一项呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442334/

相关文章:

ios - 如何根据日期(部分)对 UITableView(聊天气泡)中的消息进行分组?

android - 如何重新启动应用程序一次 - Firebase

php - 使用 javascript 更改 URL 哈希-设置后恢复为空白

javascript - 我在用 JavaScript 编写公牛和奶牛游戏时遇到问题

javascript - jquery UI Accordion 关闭问题

javascript - 使用 Webpack 构建 JS 库时向浏览器公开默认变量

java - Android并行执行多个AsyncTask

iphone - 在 iPhone 应用程序中使用异步方法调用的 FTP 文件

javascript - 将 Promise 中的值传递或访问 API

firebase - 如何更改firebase phone auth中的短信验证模板