javascript - 改造 for 循环,内部包含异步操作

标签 javascript asynchronous

我有一个对象数组,当用户单击按钮时,我需要执行以下操作:

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/

相关文章:

python - django celery get() 用于获取结果表单任务

javascript - 异步函数的行为与我对 Jest 的预期不同

Javascript,保存 onclick 中的值并将以前的值保存在数组中

javascript - 如何从外部函数访问数组?

javascript - 处理 http 调用的响应 : filter is not a function

.net - 带超时的 F# 异步工作流

javascript - 如何为 Node.js 编写异步函数

asp.net - 如何从 ASP.NET 应用程序异步调用 Web 服务?

javascript - 如何使用 jQuery 对 Twitter Bootstrap 进度条进行动画处理

javascript - 无法自动从 ng-class 添加/删除类以切换所选选项卡