草庐IT

php - 在等待 ajax.done 完成时暂停 for each 循环

coder 2024-04-18 原文

我正在使用 for each 方法遍历一组命令文件。

对于每个命令文件,在继续执行下一个命令之前,我需要等待 ajax 成功。

问题是 for each 循环在 ajax 代码完成之前移动到下一个命令。谁能提供解决方案?

对于每个循环:

$.each(cmd_files, function(index, cmd) {

          update_log('Running CMD for' + cmd)

          wait_for_cmd_complete(cmd).done(function(data){

               update_log("CMD is complete");    

          })
 })

Ajax 函数:

function wait_for_cmd_complete(cmd){

     return $.ajax({
         type: 'POST',
         data: {cmd:cmd}, 
         url: 'wait_for_cmd_complete.php'
     });  


  }

最佳答案

这根本不是您编写事件驱动操作的方式。如果您需要下一次代码迭代仅在事件之后开始,那么您就不会遍历迭代……因为那样会在事件发生之前运行所有代码!这就是事件的运作方式。

制作类似这种通用结构的东西对于每个事件运行 1 次代码迭代会更好:

var i = 0; // the index we're using
var list = []; // array of the things you plan on "looping" through
var max = list.length; // basically how many iterations to do

function nextIteration() {
    if (i >= max) return; // end it if it's done
    // do whatever you want done before the event for this iteration
    list[i].addEventListener("someevent", onEvent); // add whatever event listener
}

function onEvent() {
    // do whatever it is you want done after the event for this iteration
    i++; // up the index
    nextIteration(); // start the next iteration
}

nextIteration(); // start the first iteration manually

为了说明目的,以便您了解发生了什么,这里是您的代码,其格式与我上面的代码类似。

var i = 0; // the index we're using
update_log('Running CMDs');
var cmd; // basically a var just so we don't have to keep calling cmd_files[i]
var totalCommands = cmd_files.length; // basically how many iterations to do

function sendNextCommand() {
    if (i >= totalCommands) return; // end it if it's done
    cmd = cmd_files[i]; // again, just so we don't have to keep calling cmd_files[i]
    update_log("Waiting for CMD " + cmd + " to complete...");
    $.ajax({type:'POST', data:{cmd:cmd}, url:'wait_for_cmd_complete.php'}).done(onCommandComplete);
    // above line does what needs to be done (sends to PHP) and then adds the event listener 'done'
}

function onCommandComplete(value) {
    update_log( "    CMD complete for: " + cmd);
    i++; // up the index
    sendNextCommand(); // start the next iteration
}

sendNextCommand(); // start the first iteration manually

关于php - 在等待 ajax.done 完成时暂停 for each 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32767400/

有关php - 在等待 ajax.done 完成时暂停 for each 循环的更多相关文章

  1. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  4. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  5. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  6. ruby - Ruby 中的闭包和 for 循环 - 2

    我是Ruby的新手,有些闭包逻辑让我感到困惑。考虑这段代码:array=[]foriin(1..5)array[5,5,5,5,5]这对我来说很有意义,因为i被绑定(bind)在循环之外,所以每次循环都会捕获相同的变量。使用每个block可以解决这个问题对我来说也很有意义:array=[](1..5).each{|i|array[1,2,3,4,5]...因为现在每次通过时都单独声明i。但现在我迷路了:为什么我不能通过引入一个中间变量来修复它?array=[]foriin1..5j=iarray[5,5,5,5,5]因为j每次循环都是新的,我认为每次循环都会捕获不同的变量。例如,这绝对

  7. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

  8. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  9. ruby-on-rails - Rails 3 - 过滤器链暂停为 :authentication rendered or redirected - 2

    我仍然收到标题中的“错误”消息,但不知道如何解决。在ApplicationController中,classApplicationController在routes.rb#match'set_activity_account/:id/:value'=>'users#account_activity',:as=>:set_activity_account--thisdoesn'tworkaswell..resources:usersdomemberdoget:action_a,:action_bendcollectiondoget'account_activity'endend和User

  10. Ruby:行 "m = Hash.new {|h,k| h[k] = []}"完成了什么而 "Hash.new"没有完成? - 2

    一边学习thisRailscast我从Rack中看到了以下源代码:defself.middleware@middleware||=beginm=Hash.new{|h,k|h[k]=[]}m["deployment"].concat[[Rack::ContentLength],[Rack::Chunked],logging_middleware]m["development"].concatm["deployment"]+[[Rack::ShowExceptions],[Rack::Lint]]mendend我的问题是关于第三行。什么是传递block{|h,k|h[k]=[]}到Has

随机推荐