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.