【问题标题】:JS Execute functions in order, while passing the next function as an argumentJS 按顺序执行函数,同时将下一个函数作为参数传递
【发布时间】:2014-03-29 15:15:19
【问题描述】:

我试图通过这样做来消除“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]();
}

【问题讨论】:

  • 你只想按顺序执行几个函数?你可以用你想要的函数做一个数组,让一个函数执行数组中的第一个函数,然后删除它
  • 是的,但我想要它,以便函数本身执行下一个函数。见代码块#1
  • 另外,考虑学习 Promise 而不是滚动你自己的异步抽象 :)
  • 另外,你有一个隐式全局。

标签: javascript asynchronous


【解决方案1】:

这样的工作:

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/

【讨论】:

    【解决方案2】:

    你可以试试这个:

    function $$(){
        var i=0, ret, args = [].slice.call(arguments);
        var obj = {
            next: function() {
                ret = args[i++].call(obj, ret);
            }
        };
        obj.next();
    }
    

    并像这样使用它:

    $$(
        function() {
            console.log(Date() + ' - Function 1');
            setTimeout(this.next, 1e3); // simple async function
        },
        function(){
            console.log(Date() + ' - Function 2');
            return waitForSomethingAndReturnAValue(this.next, "I am a parameter!");
        },
        function(aValue){
            console.log(Date() + ' - Function 3');
            console.log("My value is:" + aValue);
        }
    );
    function waitForSomethingAndReturnAValue(callback, param) {
        setTimeout(callback, 2e3);
        return param + param;
    }
    

    基本上,每个函数中的返回值都作为参数传递给下一个函数。并且对下一个函数的引用是this.next

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2017-08-07
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2013-11-19
      相关资源
      最近更新 更多