Skip to content

Instantly share code, notes, and snippets.

@pedronauck
Created September 7, 2014 05:58
Show Gist options
  • Save pedronauck/d595df045eb3a617964b to your computer and use it in GitHub Desktop.
Save pedronauck/d595df045eb3a617964b to your computer and use it in GitHub Desktop.
Example using async library to avoid callback hell
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