3

I want it to wait until .update() is done before going to the next player in the otherPlayers array. I didn't know if generators or something else could work here.

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 */);
  } 
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Josh Birdwell
  • 745
  • 4
  • 21

1 Answers1

1

Something like this possibly.

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

This starts with a resolved promise, which will cause the first update to execute immediately. Each subsequent update is chained on to the resolution of the previous promise.

Bert
  • 80,741
  • 17
  • 199
  • 164