Escape from Callback Hell
You probably heard about asynchronous code and that it is hard to work with. In this article I'll share simple approach that makes working with asynchronous code easier.
Let's take a look at sample case - we need to authenticate user on the remote service, get list of his comments and render it in HTML.
There are three asynchronous functions - authenticateUser
, getComments(userId)
and renderComments(user, comments)
.
var authenticateUser = function(login, password, cb){setTimeout(function(){
var user = {id: '1', name: 'admin'}
cb(null, user)
})}
var getComments = function(userId, cb){setTimeout(function(){
var comments = [{text: 'some comment...'}]
cb(null, comments)
})}
var renderComments = function(user, comments, cb){
setTimeout(function(){
var html = user.name + ' wrote ' + comments[0].text
cb(null, html)
})
}
Now let's write code that uses these functions and handles errors properly.