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
  • 499,950
  • 69
  • 739
  • 734
Josh Birdwell
  • 633
  • 4
  • 19

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
  • 76,566
  • 15
  • 189
  • 159