这是我处理文件上传的代码:
但是由于我没有使用承诺,所以它没有按正确的顺序运行!当我上传多个文件时,代码的 ajax 部分在最后运行(我正在使用 krajee bootstrap,此代码执行实际的文件上传!)。这是代码:
$('#uploadNoteImage').on('fileloaded', function (event, file, previewId, index, reader) {
var url = noTrailingSlash(window.location.href) + '/user/notes';
console.log("1) Notes upload number: "+index);
var imgpgno = parseInt(getNotesLength(noteTitle, notesData));
console.log("2) Got page number of image "+imgpgno);
var data = {
"subject": noteTitle,
"pgno": imgpgno + 1,
"note": reader.result
};
console.log("3) Formed data object:");
console.log(data);
$.ajax({
url: url,
method: "PUT",
data: data,
success: function (data) {
console.log("4) Successfully uploaded data");
console.log(data);
toastr.success('', 'Added!');
var order = getIndexToDelete(noteTitle, notesData);
console.log("5) Fetched order number: "+order);
var id = Math.floor(Math.random() * 1000);
if (imgpgno == 0) {
console.log("6)(No notes uploaded yet state) Images before uploading"+images);
modalImg.src = reader.result;
notesData[order].data.push({
"id": id, "pgno": imgpgno + 1,
"note": reader.result
});
images = imgpgno + 1;
console.log("7)(No notes uploaded yet state) Images after uploading: "+images);
// imgpgno++;
}
else if(imgpgno!=0) {
var newPageNo=imgpgno + 1;
console.log("6)(1 note uploaded state) Pushing data with pgno: "+newPageNo);
notesData[order].data.push({
"id": id, "pgno": newPageNo,
"note": reader.result
});
images = imgpgno + 1;
console.log("7)(1 note uploaded state) Images after uploading: "+images);
}
},
error: function (err) {
toastr.error('Try again!', 'Something went wrong in uploading note!');
console.log(err);
}
});
});
我如何在此处包含承诺,以便代码以正确的顺序运行?我已经详细概述了这里的问题:AJAX 代码的延迟执行