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

时间:2019-05-21 16:02:49

标签: javascript async-await

我当前的实现无法正常工作,因为在querySnapshop.docs上的.map迭代完成之前,“ after”的console.log正在执行。在控制台中,我看到“之前”,“之后”,然后“正在删除...”

我该如何重做以具有正确的执行顺序?

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

1 个答案:

答案 0 :(得分:1)

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

(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);
})();

我显然没有尝试过实际的代码,因此可以作为启发。