javascript - JS 按顺序执行函数,同时传递下一个函数作为参数

标签 javascript asynchronous

我试图通过这样做来消除“DOOM 回调金字塔”:

$$( //my function
  function(next) { // <- next is the next function
    setTimeout(next,1000); // simple async function
  },

  function(next){ // this function is the previous's function "next" argument
    waitForSomethingAndReturnAValue(next, "I am a parameter!");
  },

  function(aValue){
    console.log("My value is:" + aValue);
  }
);

但是我已经摆弄了大约一个小时,我的代码不起作用,有什么帮助吗?这是我到目前为止得到的:

function $$(){
  for (a in arguments){
    arguments[a] = function(){
      arguments[a](arguments[Math.max(-1, Math.min(a+1, arguments.length-1))]);
    };
  }
  arguments[0]();
}

最佳答案

类似这样的东西:

function $$() {
    if (arguments.length <= 0) return;
    var args = Array.prototype.slice.call(arguments); // convert to array

    arguments[0](function () { $$.apply(null, args.slice(1)); });
}

$$(function(next) { alert("one"); next() }, function (next) { alert("two"); next() });

http://jsfiddle.net/Cz92w/

关于javascript - JS 按顺序执行函数,同时传递下一个函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732856/

相关文章:

带有 async=true 的 JQuery .ajax 总是返回错误

c# - 我需要每天花好几个小时尽可能快地发送大量 Web 请求。什么是最有效的方法?

javascript - 我想在 asp updatepanel 中使用这个 javascript 函数,详细信息如下

javascript - 可能的 Javascript 错误?

javascript - 尝试设置cookie

javascript - 从元素中选择 html 内容

javascript - JavaScript 中的异步操作。

Javascript forEach 吞咽异常

javascript - 使用 Javascript 在 CSS3 中触发翻转动画

node.js - PowerShell 的 async.parallel?