I want to console.log()
in the console.log(list)
the uploadBytes
of my image, so that I could implement it and pass it at my backend without separating it.
The code is something like this
const handleSubmitForm = e => {
e.preventDefault()
alert("Your Images Is Uploaded")
const imagesRef = ref(storage,`GALLERY/${image.name}${v4()}`)
const imagesRef2 = ref(storage,`GALLERY/${image2.name}${v4()}`)
const imagesRef3 = ref(storage,`GALLERY/${image3.name}${v4()}`)
const imagesRef4 = ref(storage,`GALLERY/${image4.name}${v4()}`)
const imagesRef5 = ref(storage,`GALLERY/${image5.name}${v4()}`)
const id = v4()
const Uploads = async() => {
const list = []
uploadBytes(imagesRef,image)
.then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log('Image uploaded' `${url}`)
const item = url
list.push(item)
})
})
uploadBytes(imagesRef2,image2)
.then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log('Image uploaded' `${url}`)
const item = url
list.push(item)
})
})
uploadBytes(imagesRef3,image3)
.then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log('Image uploaded' `${url}`)
const item = url
list.push(item)
})
})
uploadBytes(imagesRef4,image4)
.then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log('Image uploaded' `${url}`)
const item = url
list.push(item)
})
})
uploadBytes(imagesRef5,image5)
.then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
console.log('Image uploaded' `${url}`)
const item = url
list.push(item)
})
})
console.log(list)
}
Uploads()
}
My only problem here is in the const list = []
, wherein I want to append every uploadBytes
in my list, so that I will not have to repeatedly called the backend, cause Imma put a backend there in every uploadBytes
, but I want to make it more easy as just to push it in the list.
I tried to do it in async but it doesn't work out. It does just give me an empty array on it cause I don't know? I'm just thinking I need to make the uploadBytes
as async but still doesn't work.
CodePudding user response:
If I understand your question correctly you want to log the list of download URLs after all the images have been uploaded.
This requires that you handle two asynchronous operations for each upload:
- the upload of the data itself,
- the call to get the download URL.
Since you need to do this for every image, you'll need a Promise.all
, and since it's two calls, you'll need a chained then
operation.
Combining this leads to:
// Helper function to upload an image and get back its download URL
const UploadSingleImage = (ref, image) => {
return uploadBytes(ref, image).then((snapshot) => {
return getDownloadURL(ref);
})
}
const Uploads = async () => {
const list = await Promise.all([
UploadSingleImage(imagesRef, image),
UploadSingleImage(imagesRef2, image2),
UploadSingleImage(imagesRef3, image3),
UploadSingleImage(imagesRef4, image4),
UploadSingleImage(imagesRef5, image5)
]);
console.log(list)
}