[英]Using promises to execute ajax synchronously
This is my code where I handle file uploads: 这是我处理文件上传的代码:
But as I am not using promises it doesn't run in proper sequence! 但是因为我没有使用promises,所以它没有以正确的顺序运行! The ajax part of the code runs at the very end when I upload multiple files (I am using krajee bootstrap and this code does the actual file upload!). 当我上传多个文件时,代码的ajax部分在最后运行(我正在使用krajee bootstrap并且此代码执行实际的文件上传!)。 Here's the code: 这是代码:
$('#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);
}
});
});
How I can included promises here so that the code runs in proper sequence? 我如何在这里包含promises,以便代码以正确的顺序运行? I have outlined the problem here in full detail: Late execution of AJAX code 我在这里详细概述了这个问题: AJAX代码的延迟执行
Simplest way requires one little "setup" - 最简单的方法需要一点点“设置” -
var uploadInProgress = $.when();
this "primes" the uploadInProgress
variable in such a way that the first upload will begin as soon as we want it to 这将“填充” uploadInProgress
变量,以便第一次上传将在我们希望的时候开始
the whole code is not very different to the code you already have: 整个代码与您已有的代码差别不大:
var uploadInProgress = $.when();
$('#uploadNoteImage').on('fileloaded', function (event, file, previewId, index, reader) {
// here, we chain the "pending" upload to this one
uploadInProgress = uploadInProgress.then(function() {
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);
return $.ajax({
url: url,
method: "PUT",
data: data
// since we are using Promise pattern, use .then for success, and .catch for error conditions
}).then(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) { // the check is redundant since when the above if condition is false, this has to be true
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);
}
}).catch(function (err) {
// this catch ensures that the next upload will be able to run regardless of this upload's failure
toastr.error('Try again!', 'Something went wrong in uploading note!');
console.log(err);
});
});
});
Instead of the success:
/ error:
callbacks, use the fact that $.ajax
returns a Promise
, and use .then
/ .catch
- this makes it easy to chain the upload requests one after the other 取而代之的是的success:
/ error:
回调,使用的事实, $.ajax
返回一个Promise
,和使用.then
/ .catch
-这使得它很容易链上传后,其他请求一个
Note: make sure the .catch actually handles the error (ie doesn't throw one) or the promise chain will break - the code you had in error:
is fine as is 注意:确保.catch实际上处理错误(即不抛出一个)或者promise链将破坏 - 你error:
的代码error:
很好,因为它是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.