我有一个对象数组,当用户单击按钮时,我需要执行以下操作:
for (var i = 0; i < arrayItems.length; i++) {
var item = arrayItems[i];
$.post(...)
.fail(function(error) {
// Abort the for loop
})
.done(function(data) {
// Do some calculations with the item
...
// Show a dialog box to write some extra data
dialog.open(); // dialog is a Telerik Window widget
});
}
我面临的问题是对话框以异步方式打开(我使用 Telerik Window 小部件作为对话框),因此我需要转换 for 循环以使进程同步。
另一个问题:如果发布失败,如何中止 for 循环?
谁能告诉我如何实现这个目标?
谢谢。
最佳答案
您可以将循环转换为递归函数,一旦收到当前项目的响应,该函数就会调用 $.post
来获取下一个项目。如果任何时候发生失败,您只需停止递归即可中止。
function fn(items, idx) {
if (idx < items.length) {
$.post(...)
.fail(function(error) {
// Abort the process by not calling `fn` recursively
})
.done(function(data) {
dialog.open();
// call `fn` recursively for the next item
fn(items, idx + 1);
});
}
}
如果您想在对话框关闭后继续执行下一项,我确信对话框有一个 onclose
(或类似的) Hook ,您可以使用它并只需调用 fn
放在它里面。
function fn(items, idx) {
if (idx < items.length) {
$.post(...)
.fail(function(error) {
// Abort the process by not calling `fn` recursively
})
.done(function(data) {
dialog.open({
onClose: function() {
// call `fn` recursively for the next item
fn(items, idx + 1);
}
});
});
}
}
关于javascript - 改造 for 循环,内部包含异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360887/