I am trying to create a function that handles file uploads in bulk. I have what I call a floor, and each floor has rooms. Every room can have an audio file. This function should handle the upload of these files. My problem is that the updated "floor" gets written before the files have been uploaded. Meaning I can't make it work asynchronously properly.
This is my function: - tracks is an object with the keys being the index of the room and the values the files themselves (using an object and not an array because this is an updating funtction so I might not have all the rooms in this object).
export const saveFloor = (floor, tracks, cb) => async () => {
const newFloor = { ...floor };
if (tracks) {
await Object.keys(tracks).forEach(async (trackKey) => {
const track = tracks[trackKey];
const ref = storage.ref(
`/audio/floor_tracks/${floor.id}/${trackKey}/${track.name}`
);
const upload = await ref.put(track);
if (!upload) return;
const downloadUrl = await ref.getDownloadURL();
if (!downloadUrl) return;
newFloor.rooms[trackKey].track = { name: track.name, file: downloadUrl };
console.log("this is the floor", "Just finished one track");
});
console.log("this is the floor", "Just finished all tracks");
}
console.log("this is the floor", newFloor.rooms);
db.collection("floors")
.doc(floor.id)
.set(newFloor)
.then(() => {
cb();
})
.catch((e) => {
console.log("Saving to db failed", e);
});
};
I get Just finished all tracks
and newFloor.rooms
printed way before Just finished one track
.
Edit after the answer from RikkusRukkus
, this is my current function, and I am getting the error
Unhandled Rejection (TypeError): undefined is not iterable (cannot read property Symbol(Symbol.iterator))
export const saveFloor = (floor, logoFile, tracks, cb) => async () => {
const newFloor = { ...floor };
if (logoFile) {
const ref = storage.ref(`/images/floor_logos/${floor.id}`);
const upload = await ref.put(logoFile);
if (!upload) return;
const downloadUrl = await ref.getDownloadURL();
if (!downloadUrl) return;
newFloor.logo = downloadUrl;
}
if (tracks) {
await Promise.all(
Object.keys(tracks).forEach(async (trackKey) => {
const track = tracks[trackKey];
const ref = storage.ref(
`/audio/floor_tracks/${floor.id}/${trackKey}/${track.name}`
);
const upload = await ref.put(track);
if (!upload) return;
const downloadUrl = await ref.getDownloadURL();
if (!downloadUrl) return;
newFloor.rooms[trackKey].track = {
name: track.name,
file: downloadUrl,
};
console.log("this is the floor", "Just finsihed one track");
})
);
console.log("this is the floor", "Just finsihed all tracks");
}
console.log("this is the floor", newFloor.rooms);
db.collection("floors")
.doc(floor.id)
.set(newFloor)
.then(() => {
cb();
})
.catch((e) => {
console.log("Saving to db failed", e);
});
};