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 ...

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.