Javascript 如何使数组映射迭代同步?

Javascript 如何使数组映射迭代同步?,javascript,async-await,Javascript,Async Await,我当前的实现不起作用,因为“after”的console.log是在querySnapshop.docs上的.map迭代完成之前执行的。在我的控制台中,我看到“之前”、“之后”,然后是“删除…” 我如何重做此操作以获得正确的执行顺序 const uid = this.afAuth.auth.currentUser.uid; let pollIds = polls.map(poll => poll.payload.doc.id); console.log("before", pollIds

我当前的实现不起作用,因为“after”的console.log是在querySnapshop.docs上的.map迭代完成之前执行的。在我的控制台中,我看到“之前”、“之后”,然后是“删除…”

我如何重做此操作以获得正确的执行顺序

const uid = this.afAuth.auth.currentUser.uid;
let pollIds = polls.map(poll => poll.payload.doc.id);

console.log("before", pollIds);

var db = firebase.firestore();
db.collection('votes').where('uid', '==', uid).get({source: 'server'}).then((querySnapshot) => {
  let totalVotes = querySnapshot.docs.length;
  let alreadyVoted = querySnapshot.docs.map(async vote => {
    vote.ref.get().then(doc => {
      let pollId = doc.data().poll
      var index = pollIds.indexOf(pollId);
      if (index > -1) {
        console.log("removing...", pollIds[index]);
        pollIds.splice(index, 1);
      }

    });
  });
  console.log("after", pollIds);
});

您可以使用
async/await
轻松重写代码。它将变得更易于阅读、编写和维护,而且它将根据需要在消息之后记录您的

(async () => {
    console.log('before', pollIds);

    const uid = this.afAuth.auth.currentUser.uid;
    const pollIds = polls.map(poll => poll.payload.doc.id);


    const db = firebase.firestore();
    const querySnapshot = await db.collection('votes').where('uid', '==', uid).get({source: 'server'});
    const docs = querySnapshot.docs;
    const totalVotes = docs.length;

    for (const vote of docs) {
        const doc = await vote.ref.get();
        const pollId = doc.data().poll;
        const index = pollIds.indexOf(pollId);
        if (index > -1) {
            console.log('removing...', pollIds[index]);
            pollIds.splice(index, 1);
        }
    }

    console.log('after', pollIds);
})();

我显然没有尝试过实际的代码,所以把它作为灵感。

Promise.all()
地图非常感谢。