1

I am trying to eliminate the "callback pyramid of DOOM" by doing this:

$$( //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);
  }
);

BUT I have been fiddling for about an hour, and my code doesn't work, any help? this is what I got so far:

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

2 Answers2

1

Something like this works:

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/

Rajit
  • 808
  • 5
  • 9
0

You can try this:

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

and use it like this:

$$(
    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;
}

Basically, the returned value in each function is passed as the argument to the next one. And the reference to the next function is this.next.

Oriol
  • 274,082
  • 63
  • 437
  • 513