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