使用 promises 同步执行 ajax
Using promises to execute ajax synchronously
这是我处理文件上传的代码:
但由于我没有使用 promises,因此 运行 顺序不正确!当我上传多个文件时,代码 运行 的 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);
}
});
});
如何在此处包含承诺,以便代码 运行 以正确的顺序排列?我在这里详细描述了这个问题:Late execution of AJAX code
最简单的方法需要一点 "setup" -
var uploadInProgress = $.when();
这个 "primes" uploadInProgress
变量以这样的方式第一次上传将在我们想要的时候开始
整个代码与您已有的代码差别不大:
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);
});
});
});
而不是 success:
/error:
回调,使用 $.ajax
returns a Promise
的事实,并使用 .then
/ .catch
- 这使得将上传请求一个接一个地链接起来变得容易
注意:确保 .catch 确实处理了错误(即不抛出一个错误),否则承诺链将中断 - 您在 error:
中的代码没有问题
这是我处理文件上传的代码:
但由于我没有使用 promises,因此 运行 顺序不正确!当我上传多个文件时,代码 运行 的 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);
}
});
});
如何在此处包含承诺,以便代码 运行 以正确的顺序排列?我在这里详细描述了这个问题:Late execution of AJAX code
最简单的方法需要一点 "setup" -
var uploadInProgress = $.when();
这个 "primes" uploadInProgress
变量以这样的方式第一次上传将在我们想要的时候开始
整个代码与您已有的代码差别不大:
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);
});
});
});
而不是 success:
/error:
回调,使用 $.ajax
returns a Promise
的事实,并使用 .then
/ .catch
- 这使得将上传请求一个接一个地链接起来变得容易
注意:确保 .catch 确实处理了错误(即不抛出一个错误),否则承诺链将中断 - 您在 error:
中的代码没有问题