March 21, 2012

Zero nested callbacks

function init(){;
  //init code
  some.event(function callback1(){;
    // callback 1 code
    other.event(function callback2(){;
      // callback 2 code
      another.event(function callback3(){;
        // callback 3 code
      }) 
    })  
  })  
}
Instead of a lots of nested callbacks or creating a lot of named functions in your javascript (for node.js or browsers) you can use something like this:
function fullProcess(){
 this._step = ++this._step || 0;
 switch(this._step){
  case 0:
   // init code 
   some.event(fullProcess) 
  break;
  case 1:
   // callback 1 code
   other.event(fullProcess)
  break;
  case 2:
   // callback 2 code
   another.event(fullProcess)
  break;
  case 3:
   // callback 3 code
  break;
 } 
}
Be aware that the "this" keyword is referring to the global object and not the function.

3 comments:

  1. Hello

    I was just wondering, why putting a ; after the { directly ?

    Good tip btw, ty


    PS : your blog "comment as" section is so bad. I cant just put my email adresse or something to comment? I spend like 15min just to ask you this question :(

    ReplyDelete
  2. No reason, i forgot to delete it.
    The comment system is the blogger one, so blame Google. If you are logged in Google/Gmail you can comment directly.

    ReplyDelete
  3. So you take a callback and change it to be a hybrid of callbacks and automata. Callbacks certainly have poor readability, considering this being a major improvement and automata generally being regarded as having poor readability.

    ReplyDelete

You can use [CODE][/CODE] to post Javascript code.
You can start a sentence with ">" to make a quotation.