I have the following functions which I would prefer to be handled synchronously but somehow it doesnt work properly.
function upload_to_aws(data) {
return new Promise(function(resolve, reject) {
loan_application_id = $('#loan_application_id').val();
var s3BucketName = data.bucket_name;
var s3RegionName = data.region;
AWS.config.update({accessKeyId: data.key, secretAccessKey: data.secret_key, region: s3RegionName});
var s3 = new AWS.S3({params: {Bucket: s3BucketName, Region: s3RegionName}});
aws_url= []
$('.attached_image').each(function() {
if($(this).attr('src') != "/assets/upload_bg.png" && $(this).attr('src') != '' ) {
var timestamp = (new Date()).getTime();
var randomInteger = Math.floor((Math.random() * 1000000) + 1);
filename = 'self_evaluation_images/'+ loan_application_id + '_self_eval_ic_' + timestamp + '.png';
var u = $(this).attr('src').split(',')[1],
binary = atob(u),
array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var typedArray = new Uint8Array(array);
s3_upload(s3, filename, typedArray).then(function(url_aws) {
aws_url.push(url_aws);
console.log(aws_url)
console.log(aws_url.length)
})
}
})
resolve(aws_url);
})
}
function s3_upload(s3, filename, typedArray) {
return new Promise(function(resolve, reject) {
s3.putObject({Key: filename, ContentType: 'image/png', Body: typedArray.buffer, ContentEncoding: 'base64', ACL: 'public-read'},
function(err, data) {
if (data !== null) {
url_aws = s3.endpoint.href + filename;
resolve(url_aws)
}
else {
reject(err);
}
});
})
}
When this function is called,it calls the upload_to_aws
function and i want everything to be executed in that function before it returns to me the array of aws_uploaded url.
$.when(upload_to_aws(data.data)).then(function(aws_uploaded_url) {
console.log(aws_uploaded_url);
})
But what basically happens at the moment is that during when the image is being uploaded to s3, this gets called resolve(aws_url)
even before the images are uploaded to s3 hence this prints console.log(aws_uploaded_url)
as an empty array []
because the function hasnt executed completely.
Is there any other way to handle callbacks and synchronous functions in javascript?