gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:37:11 24 4
gpt4 key购买 nike

我当前的实现不起作用,因为“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com