Created
September 7, 2014 05:58
-
-
Save pedronauck/d595df045eb3a617964b to your computer and use it in GitHub Desktop.
Example using async library to avoid callback hell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var async = require('async'); | |
var Product = require('../model/Product'); | |
var Category = require('../model/Category'); | |
var Attribute = require('../model/Attributes'); | |
// bad idea | |
exports.index = function() { | |
Product.find(function(err, products) { | |
Category.find(function(err, categories) { | |
Attribute.find(function(err, attributes) { | |
res.render('index', { | |
products: products, | |
categories: categories, | |
attributes: attributes | |
}); | |
}) | |
}); | |
}); | |
}; | |
// good idea | |
exports.index = function() { | |
var getProducts = function(cb) { | |
Product.find(function(err, products) { | |
cb(null, products) | |
}); | |
}; | |
var getCategories = function(cb) { | |
Category.find(function(err, categories) { | |
cb(null, categories); | |
}); | |
}; | |
var getAttributes = function(cb) { | |
Attribute.find(function(err, attributes) { | |
cb(null, attributes); | |
}); | |
}; | |
var renderIndex = function(err, data) { | |
res.render('index', { | |
products: data.products, | |
categories: data.categories, | |
attributes: data.attributes | |
}); | |
}; | |
async({ | |
products: getProducts, | |
categories: getCategories, | |
attributes: getAttributes | |
}, renderIndex); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment