News for hackers. Stuff that matters.
Re:Ask HN: Is callback hell exaggerated? by angersock on Wednesday July 20, 2016 @10:36PM (#12134231)
So, I think an example here will help you understand.

Let's use NodeJS with Express and with pg-node. Let's say you have a database.

  1. You define an Express handler to handle a get request.
  2. In that handler, you connect to a database, which takes a callback
  3. You create a query on that connection, this takes a callback.
  4. You then write a function that feeds the query result rows into a CSV exporter, which takes a callback (because of course it does).
You now have a pyramid something like 5 levels deep. Callback hell is in fact a thing.

However, I've found that pipeline of promises almost completely solve that problem.

Re:Ask HN: Is callback hell exaggerated? by tonyle on Wednesday July 20, 2016 @11:09PM (#12134353)
I'm not sure when promises came to the javascript, but it seems weird that people would settle with callback hell for so long without even attempting to refactoring it.

I mean if I didn't have the option of using promises, I would have probably written something like this.

function handler(callback){

  var state={};

  function logic(step,err,data){  
    if(!step){
      connectToDb("somedatabase",logic.bind(state,1))
    }
    
    if(step==1){
      if(err) callback("error1")
      state.dbInstance=data
      state.dbInstance.query("someQuery",logic.bind(state,2))
    }
    
    if(step==2){
      if(err) callback("error2")
      csvExporter(data,logic.bind(state,3))
    }

    if(step==3){
      if(err) callback("error3")
      callback(data)
    }
  }
  logic()
}
Re:Ask HN: Is callback hell exaggerated? by sleazebreeze on Thursday July 21, 2016 @01:26AM (#12134932)
That looks like a very similar pattern that I've seen commonly used in Go. It makes for very clear code and explicit error handling. I kind of like it for the clarity, even if it isn't "elegant" or concise.
Re:Ask HN: Is callback hell exaggerated? by xyzzy123 on Thursday July 21, 2016 @03:45AM (#12135372)
Did you mean return callback("error1") etc? Forgetting the return is a classic bug when you're in callback hell...
Re:Ask HN: Is callback hell exaggerated? by angersock on Thursday July 21, 2016 @11:35AM (#12137536)
Yeeeeep.

I think the example and your reply neatly illustrate the problem.

Re:Ask HN: Is callback hell exaggerated? by gravypod on Wednesday July 20, 2016 @10:54PM (#12134289)
Promise frameworks do seem to lend well to this sort of problem and I'm excited to see these developed.
Re:Ask HN: Is callback hell exaggerated? by smt88 on Thursday July 21, 2016 @04:43AM (#12135562)
There are tons of promise libraries and most major frameworks either support promises or can be "promisified" easily