[英]async/await with firebase storage
我有一個接收數據的 function,我使用異步 promise 來獲取文檔item.poster = await Promise.all(promises)
的鏈接,然后將數據添加到數組並沒有時間,大批。 但是,如果我刪除 function 以獲取文檔鏈接,那么一切正常。 在調試模式下,我可以看到所有數據都很好,但為什么我得到一個空數組?
async FetchData({ state, commit }, to) { try { const q = query(collection(db, to)); await onSnapshot(q, (querySnapshot) => { let data = []; querySnapshot.forEach(async (doc) => { let promises = []; let item = { id: doc.id, name: doc.data().name, slug: doc.data().slug, country: doc.data().country, duration: doc.data().duration, year: doc.data().year, video: doc.data().video, genres: doc.data().genres, actors: doc.data().actors, }; if (to === "films") { const starsRef = ref(storage, `images/${doc.id}/poster.png`); promises.push(getDownloadURL(starsRef)); item.poster = await Promise.all(promises); } data.push(item); }); commit("setData", { data, to }); }); } catch (err) { console.error(err); } }
forEach
和async
不能很好地協同工作, forEach 是不可等待的。 但解決方案很簡單, .map
和Promise.all()
:
async FetchData({ state, commit }, to) {
try {
const q = query(collection(db, to));
await onSnapshot(q, (querySnapshot) => {
const allPromises = querySnapshot.docs.map(async (doc) => {
let item = {
id: doc.id,
name: doc.data().name,
slug: doc.data().slug,
country: doc.data().country,
duration: doc.data().duration,
year: doc.data().year,
video: doc.data().video,
genres: doc.data().genres,
actors: doc.data().actors
};
if (to === "films") {
const starsRef = ref(storage, `images/${doc.id}/poster.png`);
item.poster = await getDownloadURL(starsRef);
}
return item;
});
Promise.all(allPromises)
.then((data) => commit("setData", { data, to }))
.catch(console.error);
});
} catch (err) {
console.error(err);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.