我正在構建一個表單,用戶需要在其中輸入資訊來創建城市檔案。用戶還需要上傳多張城市的照片。提交表單時,會在 firestore 中創建一個新的城市檔案,然后將每張照片上傳到關聯的 firebase 存盤,最后將一個photosURLs包含所有照片 URL 的新欄位添加到城市檔案中。
這是我的代碼:
async function addDocument() {
const docRef = await addDoc(collection(db, "cities"), {
name: "Tokyo",
country: "Japan"
});
return docRef
}
async function UploadMultiplePhotos(docRef) {
var photos = []
for (var i = 0; i < files.value.length; i ) { // files.values contains all the files objects
const file = files.value[i];
refStorageFunction(
storage,
"cities/"
docRef.id
"/"
file.name
);
uploadBytes(storageRef, file).then((snapshot) => {
getDownloadURL(snapshot.ref).then((downloadURL) => {
photos.push(downloadURL)
});
});
}
return Promise.resolve(photos)
}
async function updateDocument(docRef, photos) {
await updateDoc(docRef, { photosURLs: photos });
}
function createCity() {
addDocument().then((docRef) => {
UploadMultiplePhotos(docRef).then((photos) => {
updateDocument(docRef, photos).then(() => {
router.push($CITY_PATH)
})
})
})
}
我的問題是photosURLs城市檔案中的結果欄位為空。看來我的函式UploadMultiplePhotos不會等待photos陣列完全填充。
uj5u.com熱心網友回復:
如果你設定斷點并在除錯器中運行代碼,或者添加一些放置良好的日志陳述句,你會看到你在呼叫return Promise.resolve(photos)之前運行photos.push(downloadURL):所以你總是用一個空陣列決議。
一個簡單的解決方案是使用await而不是then():
async function UploadMultiplePhotos(docRef) {
var photos = []
for (var i = 0; i < files.value.length; i ) { // files.values contains all the files objects
const file = files.value[i];
refStorageFunction(
storage,
"cities/"
docRef.id
"/"
file.name
);
const snapshot = await uploadBytes(storageRef, file)
const downloadURL = await getDownloadURL(snapshot.ref)
photos.push(downloadURL)
}
return photos
}
uj5u.com熱心網友回復:
嘿,我遇到了同樣的問題,請您幫幫我。這是我從您那里復制并嘗試過的問題,但對我不起作用,請訪問此。Firebase 更新檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414934.html
標籤:
