Reputation: 139
I'm struggling to fetch the download image URL in firebase storage.
What I wanted to achieve with this code is to upload two images one after another and to push the image URL to the array.
However, my code doesn't work correctly as asynchronous. Ther result after Promise.all() suppose to return the array with URL. I'll appreciate if someone guides me to solve this issue.
const handleUpload = () => {
Promise.all([uploadImage(window1Image), uploadImage(window2Image)])
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
};
const uploadImage = (image) => {
const uuid = Date.now() + uuidv4();
const imageToServer = storage.ref(`images/${uuid}`).put(image);
imageToServer.on(
'state_changed',
(snapshot) => {
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
},
(error) => {
console.log(error);
},
() => {
storage
.ref('images')
.child(uuid)
.getDownloadURL()
.then((data) => data);
},
);
};
Upvotes: 2
Views: 897
Reputation: 83068
You should use the then()
method of UploadTask
which "behaves like a Promise, and resolves with its snapshot data when the upload completes".
The following should work (untested):
const handleUpload = () => {
Promise.all([uploadImage(window1Image), uploadImage(window2Image)])
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
};
const uploadImage = image => {
const uuid = Date.now() + uuidv4();
const imageToServer = storage.ref(`images/${uuid}`).put(image);
return imageToServer.then(uploadTaskSnapshot => {
return uploadTaskSnapshot.ref.getDownloadURL();
});
};
Upvotes: 5