我無法將 getDownloadURL 回傳的 URL 附加到 imageLinks 狀態。我想繼續使用包含所有 URL 的 imageLinks 狀態,但代碼似乎繼續運行并且不等待它回傳 URL。我如何等待它回傳鏈接然后將其附加到狀態?
const [imageLinks, setImageLinks] = useState([]);
for (let i = 0; i < 5; i ) {
if (images[i] !== null) {
const fileName = new Date().getTime() images[i].name;
const storage = getStorage(app);
const storageRef = ref(storage, fileName);
const uploadTask = uploadBytesResumable(storageRef, images[i]);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
switch (snapshot.state) {
case "paused":
console.log("Upload is paused");
break;
case "running":
console.log("Upload is in progress");
break;
default:
}
},
(error) => {
alert("Images failed to upload. " error.message);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
setImageLinks((imageLinks) => [...imageLinks, downloadURL]);
});
}
);
}
}
console.log(imageLinks); //returns empty array
uj5u.com熱心網友回復:
通過快速掃描UploadTask
回傳的類uploadBytesResumable
,它實作了 的所有要求方法Promise
。這意味著您可以將其視為上傳完成的承諾,而不是實作其狀態回呼。
這反過來又允許您使用Promise.all
等待所有上傳完成并獲取所有下載 URL。
let promises = [];
for (let i = 0; i < 5; i ) {
if (images[i] !== null) {
const fileName = new Date().getTime() images[i].name;
const storage = getStorage(app);
const storageRef = ref(storage, fileName);
const uploadTask = uploadBytesResumable(storageRef, images[i]);
const urlTask = uploadTask.then(() => storageRef.getDownloadURL())
promises.push(urlTask);
}
}
Promise.all(promises).then((downloadUrls) =>
console.log(downloadUrls);
setImageLinks(downloadUrls);
});
如果您處于支持async
/的環境/背景關系中await
,您也可以使用await
instead of then
。在這種情況下,您可以修改以上內容,但您甚至可以放棄Promise.all
并執行以下操作:
const storage = getStorage(app);
let urls = [];
for (let i = 0; i < 5; i ) {
if (images[i] !== null) {
const fileName = new Date().getTime() images[i].name;
const storageRef = ref(storage, fileName);
await uploadBytesResumable(storageRef, images[i]);
const url = await storageRef.getDownloadURL();
urls.push(url);
}
}
console.log(downloadUrls);
setImageLinks(downloadUrls);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535476.html
標籤:Google Cloud Collective javascript反应火力基地firebase 存储