I am working with React backed with Firebase. I am using an asynchronous firebase function to get the download URL for a file that I add. This function runs multiple times inside a for loop and to keep everything synchronized I use 'async' and 'await' to wait for the file to be added before moving on to the next entry in the loop. But the array, 'uploads', that I am populating, in the end, comes out empty after this entire loop is done. Is it not working because await is inside of then. If not, how can I do this?
_handlePost = () => {
var fs = this.props.firebase.getFS();
let uploads = [];
// if any files attached to post
if (this.state.allFiles.length > 0) {
const currentComponent = this;
let files = this.state.allFiles;
for (let i=0; i<files.length; i++) {
var file = files[i];
var type = file.type;
var file_parts = type.split("/");
var type = "." + file_parts[1];
var cat = file_parts[0];
var file_path = '';
// save to correct firebase storage folder
if (cat === "image")
file_path = "image/";
else if (cat === "video")
file_path = "videos/";
else
file_path = "test_file_upload";
const uploadtask = currentComponent.props.firebase.getStorageRef(file_path + file.name).put(file);
uploadtask.on(
'state_changed',
null,
(error) => { console.log(error); },
() => {
currentComponent.props.firebase.getStorageRef(file_path).child(file.name).getDownloadURL()
.then(function(url) {
// add to content collection
fs.collection("content").add({
category: cat,
file_name: file.name,
file_type: type,
time_uploaded: new Date(Date.now()),
user_id: currentComponent.props.userId,
url_link: url
})
.then(async function(doc) {
console.log("Added to content collection!");
const attachment = {
category: type,
content_id: doc.id,
url_link: url
};
uploads.push(attachment);
});
});
}
);
};
}
console.log("Done");
console.log(uploads);
// add wall_posts to database
fs.collection("wall_posts").add({
attachments: uploads,
body_text: this.state.post_text,
posterid: this.props.userId,
time_posted: new Date(Date.now()),
user_id_wall: this.props.userId
})
.then(function() {
console.log("Post successful!");
});
}