5 ms·
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 refacto
by tonyle 10y ago
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()
}
- sleazebreeze 10y agoThat 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.
- deleted 10y ago[deleted]
- xyzzy123 10y agoDid you mean return callback("error1") etc? Forgetting the return is a classic bug when you're in callback hell...
- angersock 10y agoYeeeeep. I think the example and your reply neatly illustrate the problem.