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

标签 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);

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轻松重写代码。它将变得更容易阅读、编写和维护,而且它会根据需要记录您的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);
})();

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

关于javascript - 如何使数组映射迭代同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56242266/

相关文章:

c# - 任务 - 属性分配

javascript - 巴别尔.获取节点的第一个子节点。遵循访客模式

javascript - 在 CSS 中插入 JS

javascript - 如何在同步模式下获取 outputStream block ?

c# - 等待和异步阻塞 UI

python - 如何等待 python 中的任务列表?

javascript - jQuery "by attribute"选择器

javascript - 查找不包括少数键的对象总和

javascript - 使用嵌套/链接保存解析无响应

c# - 查找并行异步任务的结果