草庐IT

javascript - 在javascript中执行函数队列

coder 2024-07-22 原文

我正在尝试创建一个包含多个函数的函数队列。 创建后,我想依次执行每个功能。 但是这些函数内部有延迟指令,所以我想等待每个函数完成执行后再继续。

我的尝试:

var funqueue = [];
funqueue.push( function() {fun1() });
funqueue.push( function() {fun2() });
funqueue.push( function() {fun3() });
executeFunctionQueue(funqueue);

执行函数在哪里:

function executeFunctionQueue(funqueue){
    var fun1=funqueue.pop;
    $.when(fun1()).then(executeFunctionQueue(funqueue));
}

但这行不通。 我应该怎么做?

最佳答案

尝试使用 .queue() , .promise() ;另见 Change easing functions on animations in jQuery queue

function fun1() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(1)
    }, 1500)
  }).promise().then(msg)
}

function fun2() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(2)
    }, 1500)
  }).promise().then(msg)
}

function fun3() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(3)
    }, 1500)
  }).promise().then(msg)
}

var funqueue = [];
funqueue.push(function() {
  return fun1()
});
funqueue.push(function() {
  return fun2()
});
funqueue.push(function() {
  return fun3()
});

function msg(data) {
   if (data === "complete") console.log(data)
   else $("body").append(data + "<br>")
}

function executeFunctionQueue(funqueue) {
  var deferred = funqueue.pop();
  return deferred().then(function() {
      // set `this` within `$.queue()` , `.then()` to empty object `{}`,
      // or other object
      return $({}).queue("fun", $.map(funqueue, function(fn) {
        return function(next) {
          // return `next` function in `"fun"` queue
          return fn().then(next)
        }
      })).dequeue("fun").promise("fun")
      .then(function() {
        // return "complete" string when `fun` queue empty
        return "complete"
      })
    });
}

executeFunctionQueue(funqueue)
.then(msg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>


或者,使用 $.when()

function executeFunctionQueue(funqueue) {
  return $.when(!!funqueue[funqueue.length - 1] 
                ? funqueue.pop().call().then(function() {
                  return executeFunctionQueue(funqueue)}) 
                : "complete")
}

executeFunctionQueue(funqueue)
.then(function(complete) { 
  console.log(complete) 
});

function fun1() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(1)
    }, 1500)
  }).promise().then(msg)
}

function fun2() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(2)
    }, 1500)
  }).promise().then(msg)
}

function fun3() {
  return $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(3)
    }, 1500)
  }).promise().then(msg)
}

var funqueue = [];
funqueue.push(function() {
  return fun1()
});
funqueue.push(function() {
  return fun2()
});
funqueue.push(function() {
  return fun3()
});

function msg(data) {
  if (data === "complete") console.log(data)
  else $("body").append(data + "<br>")
}

function executeFunctionQueue(funqueue) {
  return $.when(!!funqueue[funqueue.length - 1] 
                ? funqueue.pop().call().then(function() {
                  return executeFunctionQueue(funqueue)}) 
                : "complete")
}

executeFunctionQueue(funqueue)
.then(msg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

关于javascript - 在javascript中执行函数队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028368/

有关javascript - 在javascript中执行函数队列的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  3. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  7. ruby - 分布式事务和队列,ruby,erlang,scala - 2

    我有一个涉及多台机器、消息队列和事务的问题。因此,例如用户点击网页,点击将消息发送到另一台机器,该机器将付款添加到用户的帐户。每秒可能有数千次点击。事务的所有方面都应该是容错的。我以前从未遇到过这样的事情,但一些阅读表明这是一个众所周知的问题。所以我的问题。我假设安全的方法是使用两阶段提交,但协议(protocol)是阻塞的,所以我不会获得所需的性能,我是否正确?我通常写Ruby,但似乎Redis之类的数据库和Rescue、RabbitMQ等消息队列系统对我的帮助不大——即使我实现某种两阶段提交,如果Redis崩溃,数据也会丢失,因为它本质上只是内存。所有这些让我开始关注erlang和

  8. ruby - 检查是否通过 require 执行或导入了 Ruby 程序 - 2

    如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby​​文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否

  9. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  10. postman——集合——执行集合——测试脚本——pm对象简单示例02 - 2

    //1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json

随机推荐