I have created a Google Apps Script web application for uploading images to my Google Drive. It has a lot of rows, each row has an input tag for uploading file. I created an only one submit button to upload all chosen images in one time. However, I would like each row to upload each image in order and then delete that row when it was uploaded successfully in order as well. The problem is I can't find the right way to use async/await function to upload the images to Drive with FileReader because when I run the script, It's still work as asynchronous function.
async function uploadImage() {
var row = document.getElementsByClassName('row');
var file = document.getElementsByClassName('img-file');
var name = document.getElementsByClassName('img-name');
for (let i=0; i<row.length; i++) {
var image = file[i].files[0];
if (image) {
var reader = new FileReader();
reader.readAsDataURL(image);
reader.onloadend = async (event) => {
await new Promise((resolve, reject) => {
google.script.run.withSuccessHandler(r => resolve())
.uploadImgToDrive(name[i].value, event.target.result)
}).then(() => row[i].innerHTML='');
}
}
}
}
uploadImgToDrivemight return earlier for image5, while image1 might finish later even though image1 started uploading before image5. Synchronizing or ordering it might take more time. Parallel operations are faster.