|
Callback spaghetti is a sign that you're doing something wrong. The first example from this page shows a request handler initialising a database connection and then executing a query. That's terrible separation! Callbacks "spaghetti" actually does a great job of highlighting when you're not abstracting enough, any more than about 5 indents and you should be seriously considering refactoring your approach. Thus app.get('/price', function(req, res) {
db.openConnection('host', 12345, function(err, conn) {
conn.query('select * from products where id=?', [req.param('product')], function(err, results) {
conn.close();
res.send(results[0]);
});
});
});
becomes something like app.get('/price', function(req, res) {
products.fetchOne(function(err, product) {
res.render('product', { product: product });
});
});
Also, as other posts on this page mentioned, try{}catch{} is not how errors are handled in Node.JS, plenty of async operations will gain a fresh stack, and cannot be caught in this way. |