我需要實作這個異步功能,
const uploadImage = async () => {
const filename = new Date().getTime() photo!.name
const storage = getStorage(app)
const storageRef = ref(storage, filename)
const uploadTask = uploadBytesResumable(storageRef, photo!);
uploadTask.on('state_changed',
(snapshot) => {},
(error) => {
console.log("error while uploading photo", error)
},
async () => {
photoUrl = await getDownloadURL(uploadTask.snapshot.ref);
console.log("getDownloadURL", photoUrl)
return photoUrl
}
);
}
這是將影像上傳到 Firebase-Storage 的功能。在這里我需要回傳“photoUrl”。我需要像這樣呼叫函式,
const res = await uploadImage(photo)
我該怎么做呢?上傳的圖片的 URL 應該從函式回傳。
uj5u.com熱心網友回復:
回傳的物件uploadBytesResumable也是一個承諾,所以你可以await這樣然后呼叫getDownloadURL:
const uploadImage = async () => {
const filename = new Date().getTime() photo!.name
const storage = getStorage(app)
const storageRef = ref(storage, filename)
const uploadTask = uploadBytesResumable(storageRef, photo!);
await uploadTask;
photoUrl = await getDownloadURL(uploadTask.snapshot.ref);
return photoUrl
}
實際上,您甚至不需要對任務的參考,因為您已經有了storageRef,上面的內容可以簡寫為:
const uploadImage = async () => {
const filename = new Date().getTime() photo!.name
const storage = getStorage(app)
const storageRef = ref(storage, filename)
await uploadBytesResumable(storageRef, photo!);
return await getDownloadURL(storageRef);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482089.html
