5 minutes to Save you from callback hell

Sarah Muenzinger

       SarahMunzi

What's a Callback?

Javascript allows for asynchronous calls

that work something like this

 

console.log("First");

TweetDatabase.getTweets(function(err, tweets){
    console.log("Third!");
    console.log(tweets);
});

console.log("Second!");

Callbacks Don't Seem So bad?

TweetDatabase.getTweet(function(err, tweet){
  
    tweet.getAllReTweets(function(err, retweets){

        retweets.getUsers(function(err, users){

              users.followAll();
        })
    })
})
    

WhY, you no bubble?

try {
    TweetDatabase.getTweet(function(err, tweet){
      
        tweet.getAllReTweets(function(err, retweets){
    
            retweets.getUsers(function(err, users){
    
                  users.followAll();
            })
        })
    })
}
catch(err) {
    console.log("nested errors won't bubble! :(")
}    

The dark Side of Callbacks

TweetDatabase.getTweet(function(err, tweet){
    if(err){
        console.log("we found an err", err)
    }   
    tweet.getAllReTweets(function(err, retweets){
        if(err){
            console.log("we found an err", err)
        }
        retweets.getUsers(function(err, users){
            if(err){
                console.log("we found an err", err)
            }
            users.followAll();
        })
    })
})
    

Wouldn't It Be Nice...

//somewhere earlier in the code
var users = retweets.getUsers();

//somewhere later in the code,
// maybe even in another file
users.followAll();

    

With PRomises, You Can.

//somewhere earlier in the code
var promisedUsers = retweets.getUsers().then()

...

promisedUsers.then(function(users){
    users.followAll();
})

    

.then() to save the Day

TweetDatabase.getTweet()
.then(function(tweets){
    return tweet.getAllReTweets();
})
.then(function(retweets){
    return retweets.getUsers();
})
.then(function(users){
    users.followAll();
})
.catch(function(err){
    console.log("we found an err", err)
})

    

Don't Do this

TweetDatabase.getTweet()
.then(function(tweets){
    tweet.getAllReTweets()
    .then(function(retweets){
        retweets.getUsers()
            .then(function(users){
                users.followAll();
            })
    })

})
.catch(function(err){
    console.log("we found an err", err)
})

    

Do Keep LEarning

Sarah Muenzinger

sarah.muenzinger@gmail.com

   SarahMunzi

5 Minutes to Save you From CallBack Hell

By Sarah Muenzinger

5 Minutes to Save you From CallBack Hell

  • 2,083