I have the following algorithm:
// Main Function
// Get some local data
// Convert to some format I need to edit
// Loop through user's local images
// Edit the converted data to add the image's names to it
// Convert IMAGE to base64 and add result into zip file
that.uriToBase64(imageFilePath).then((result) => {
console.log("image as base64: ", result);
zip.file(arrayItem2.name, result, {base64: true});
});
// Convert data again to save it
// Add data to zip file
// Generate zip file and save it in user's local storage
//uriToBase64() function
My problem is:
The step āAdd data to zip fileā happens before the images are added to zip file. Although the āConvert IMAGE to base64ā step has a .then, everything inside happens only after everything is finished. In this case, my zip file is being saved without the images. I tried to make this step work synchronously, using async/await syntax in countless ways, but I couldnāt make it work the way I expected, which is adding the image data inside the zip file within each iteration.
Since the result of uriToBase64()
function is a Promise, using .then
to get the result data should āpauseā the loop until the data is added by the zip.file()
command, then iterate with the next image, right? If not, what is the correct way to wait for it, taking into account the current structure of the algorithm?
Updates:
Update1
I tried some nasty things to make this work, unsuccessful again.
My new algorithm:
// Main Function
// Get some local data
// Convert to some format I need and add to a global variable
// Loop through user's local images
// Add +1 to new global variable 'imageCounter'
// Edit the converted data (now in global variable) to add the image's names to it
// Convert IMAGE to base64 and add result into zip file
that.uriToBase64(imageFilePath).then((result) => {
console.log("image as base64: ", result);
zip.file(arrayItem2.name, result, {base64: true});
that.prepareForWrite();
// Check if this is the last iteration and run function again.
if (thisIsLastIteration == true) { that.prepareForWrite(); }
});
//prepareForWrite() function
// imageCounter - 1
// if imageCounter < 1
// Convert data again to save it
// Add data to zip file
// Generate zip file and save in user's local storage
//uriToBase64() function
This way I receive all the data correctly, but the āGenerate zip file and save it in userās local storageā is adding only the first image, and it ends corrupted.