O'Reilly logo

Async JavaScript by Trevor Burnham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Un-nesting Callbacks

The most common anti-pattern in JavaScript is nesting callbacks within callbacks. Remember the Pyramid of Doom from the introduction? Let’s look at a concrete example that you might see in a Node server.

 
function​ checkPassword(username, passwordGuess, callback) {
 
var​ queryStr = ​'SELECT * FROM user WHERE username = ?'​;
 
db.query(selectUser, username, ​function​ (err, result) {
 
if​ (err) ​throw​ err;
 
hash(passwordGuess, ​function​(passwordGuessHash) {
 
callback(passwordGuessHash === result[​'password_hash'​]);
 
});
 
});
 
}

Here we’ve defined an async function (checkPassword), which fires another async function (db.query), which potentially fires another async function (hash). (It’s impossible to know for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required