【发布时间】:2018-06-13 13:55:20
【问题描述】:
我希望同步处理以下函数,但不知何故无法正常工作。
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);
}
});
})
}
当调用此函数时,它会调用 upload_to_aws 函数,我希望在它返回 aws_uploaded url 数组之前在该函数中执行所有操作。
$.when(upload_to_aws(data.data)).then(function(aws_uploaded_url) {
console.log(aws_uploaded_url);
})
但目前基本上发生的情况是,在将图像上传到 s3 期间,即使在图像上传到 s3 之前,它也会被称为 resolve(aws_url),因此这会将 console.log(aws_uploaded_url) 打印为空数组 [],因为该函数尚未完全执行。
还有其他方法可以在javascript中处理回调和同步函数吗?
【问题讨论】:
-
您应该将
resolve(aws_url);放在s3_upload承诺的then函数中
标签: javascript jquery asynchronous es6-promise