I am uploading files from angular. So I made a function name uploadFile() which return an object containing a Boolean and URL of the uploaded file. But the problem is the function returns Promise before AWS S3 API call is not finished. I made another function named uploadFileToAwsS3(). the second function calls the first one within a for lop.. now I want to return from the uploadFileToAwsS3() if all calls within for loop is finished. here is my code..
function uploadFile()
`
uploadFile(file: any): Promise<{ status: boolean, message: string }> {
const self = this;
const contentType = file.type;
let url = '';
let todayFolder = '20220917';
let fileName = (moment().month() + 1).toString() + moment().date().toString() +
moment().year().toString() + '.' + (file.name.split('.').pop());
const bucket = new S3(
{
accessKeyId: 'my accessKey',
secretAccessKey: 'my secretAccessKey',
region: 'region'
}
);
const params = {
Bucket: 'bucketName',
Key: 'key',
Body: file,
ACL: 'public-read',
ContentType: contentType
};
return new Promise((resolve, reject) => {
bucket.upload(params, function (err: any, data: any) {
if (err) {
console.log(err);
return reject({ status: false, message: err });
}
url = 'https://' + 'bucketName' + '.' + 'regionEndpoint' + '/' +
'topDirectory' + '/Appraisal/' + todayFolder + '/' + fileName;
console.log(url);
return resolve({ status: true, message: url });
})
});
}
`
function uploadFileToAwsS3()
`
uploadFileToAwsS3() {
return new Promise<{ isSuccessfull: boolean }>((resolve, reject) => {
for (let index = 0; index < this.selectedFiles.length; index++) {
this.awsS3Service.uploadFile(this.selectedFiles[index])
.then(response => {
if (!response.status) {
this.errorToast(response.message);
resolve({ isSuccessfull: false });
} else {
this.awsUrls.push(response.message);
}
});
}
setTimeout(() => {
resolve({ isSuccessfull: true });
}, 1000);
});
}
`
which function is not working properly I don't know. may be the uploadFileToAwsS3() is returning after 1s whether the call within for loop is completed or not. So I want to make both synchronous. if aws api call is finished only then the uploadFile() function will return promise. and if all the call to the uploadFile() function within for loop is finished, only then uploadFileToAwsS3() function will return promise.
Please help if anyone can...