我是Promises的新手,我确信我的代码出错了。
结果是正确的但我的console.log中有Uncaught (in promise)
警告。
这里发生的是用户可以提交一个表单,其中包含一些required
字段,一些optional
字段和一个图像。
在提交时,我得到的图像经过压缩,调整大小和定向,以便以少量的Kbs上传到服务器。
在coontroller中我验证代码如上所述,有些字段是必需的,所以在Ajax调用的error
情况下,如果字段丢失,我会得到textStatus。
此代码会发生的情况是,如果用户输入图像但没有或某些必填字段,则XHR textstatus错误对象显示为Uncaught (in promise)
,(缺少必填字段)。
我错过了你如何处理承诺中的错误(拒绝?)所以我真的不知道如何解决这个错误。
我的猜测是,如果用户提交图像而不是必需的字段,则应该有一种方法可以在承诺期间检查它,以便即使用户提交图像也会被拒绝(因为单独的图像不够) 。这是用reject
完成的吗?但是哪里?你怎么在.then()之后调用错误?
如果用户提交了一些必填字段或所有字段而不是图像,该怎么办?如果我让承诺运行,我在承诺中出现undefined
错误,这就是为什么我添加了一个检查以查看是否有任何文件以及它是否是图像。
这是我的剧本:
$(document).ready(function () {
$("#AddModel").on("submit", function (e) {
e.preventDefault();
// gets the file from the form input
var files = $('#modelpic').prop('files');
var form = $(this);
// this strips the submitted form from the file and returns a new form with all the
// inputs but the file
var processedFormData = noFileFormData(form[0]);
// only if there's a file and it's an image
if( files.length !== 0 && /^image/.test(files[0].type)){
//this calls the promise that manipulates the image and returns a blob
processImage(files[0]).then(([img, ia])=> {
processedFormData.append('image', ia, 'processed.jpg');
return $.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
cache: false,
data: processedFormData,
success: function (data) {
//displays preview of the post
},
error: function (textStatus) {
//displays errors
}
});
});
}else{
//displays an error re the image is not present.
// Now this is not optimal as the image is not the only required field
}
});
});
这是准备被操纵图像的promise函数,它调用其他函数进行实际处理:
function processImage(file) {
return new Promise(function (resolve, reject) {
if (file.type.match('image.*') && file.length != 0) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
var base64img = this.result;
var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(this.result));
var srcOrientation = exif.Orientation;
resetOrientationResizeCompress(base64img, srcOrientation).then((img)=> {
dataURItoBlob(img).then((ia)=> {
resolve([img, ia]);
});
});
};
}else{
//don't really know what to do here really, or if this is the way
reject();
}
});
}
答案 0 :(得分:3)
它告诉您,您没有发现错误拒绝,请将.catch
附加到processImage(files[0])
承诺。