I have been trying to find a solution to a problem regarding an asynchronous method, I have tried various types of loops, using async/await, as well as Promisies, but none I try seem to work for me.
So I have my first method:
const postApplication = async (params...): Promise<DocumentReference> => {
const formData = await prepareData(someParams...)
{rest of method...}
}
I then have my prepareData
function, which I believe is where my issue:
P.S. I am only keeping the information that I think is necessary to make it simpler.
const prepareData = async (params...) => {
const formData = new FormData();
{some synchronous code...}
for await (const field of allCustomFields) {
if (field.identifier === someProperty) {
formData.append("fieldName", field)
} else {
for await (const value of field.value) {
const storage = getStorage();
if (value) {
const fileInfo = value as FileValue;
const imageName = fileInfo.firebaseStoragePath
?.split("mutable/")
.pop();
getDownloadURL(
ref(storage, `users/${user?.id}/mutable/${imageName}`)
).then((url) => {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = (event) => {
const file = xhr.response;
const extension = file.type.split("image/").pop();
formData.append(
"filesToUpload",
file,
`${field.identifier}-${docCounter}.${extension}`
);
docCounter += 1;
};
xhr.open("GET", url);
xhr.send();
});
}
}
}
}
return formData;
}
So the problem I am having, is that formData is being returned before the files I am retrieving from Firestore have been appended to formData
. I have tried each of the loops in a Promise
and then calling await Promise.all(nameOfConst)
before returning formData
, but none seem to work.
I appreciate anybody that can offer some help,
Thanks