Created
August 21, 2015 10:06
-
-
Save Lazhari/52ce39fe12cd03246a1f to your computer and use it in GitHub Desktop.
Wonderful async Example
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 countUser = function (callback) { | |
database.getCollection('User').find(function (err, nbUsers) { | |
if (err) return callback(err); | |
return callback(null, nbUsers.length); | |
}); | |
}; | |
var countRestaurantByCity = function(city, callback) { | |
database.getCollection('Restaurant').count({'adresse.ville': city}, function (err, nbR) { | |
if (err) return callback(err); | |
return callback(null, nbR); | |
}); | |
}; | |
var countRestaurant = function (callback) { | |
database.getCollection('Restaurant').count(function (err, nbR) { | |
if (err) return callback(err); | |
return callback(null, nbR); | |
}); | |
}; | |
exports.testAsyncSeries = function (req, res, next) { | |
var city = req.query.city; | |
async.series({ | |
nbUsers:async.apply(countUser), | |
nbR:async.apply(countRestaurant), | |
nbRC: async.apply(countRestaurantByCity, city) | |
}, function (err, results) { | |
if (err) return res.send(err); | |
return res.send(results); | |
}) | |
}; | |
exports.testAsyncWaterfall = function (req, res, next) { | |
async.waterfall([ | |
function(callback) { | |
database.getCollection('User').find({role:20}) | |
.select('_id login') | |
.limit(10) | |
.exec(function(err, users) { | |
return callback(err, users); | |
}) | |
}, | |
function(users, callback) { | |
async.map(users, function(user, mappingUserRestaurant){ | |
database.getCollection('Restaurant').count({'pro': user._id}) | |
.exec(function(err, nbRestaurants) { | |
var userObj = {}; | |
userObj[user.login] = nbRestaurants; | |
return mappingUserRestaurant(err, userObj); | |
}) | |
}, function(err, result) { | |
return callback(err, result); | |
}) | |
} | |
], function (err, result) { | |
res.json(result); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment