I'm trying to initialize two input with autocomplete with this library. When I load my page, I will trigger an Ajax to initialize two input text.
But I don't know how I can detect when all my mongoose find are completed.
Here is my server side code :
app.post('/init/autocomplete', function(req, res){
var autocomplete = {
companies: [],
offices: []
};
// Find all companies
Company.find({}, function(err, companies) {
if (err) throw err;
companies.forEach(function(company) {
autocomplete.companies.push({value: company.name})
});
console.log('One');
});
// Find all offices
Office.find({}, function(err, offices) {
if (err) throw err;
offices.forEach(function(office) {
autocomplete.offices.push({value: office.name})
});
console.log('Two');
});
console.log('Three');
// res.json(autocomplete);
});
I know than the find method is async. That is why I see my console.log() in this order :
Three
One
Two
How can I do to trigger console.log('Three');
when the Company.find
and Office.find
are finished ?
I want to see the console.log('Three');
at the last position.
Edit :
I think I can do this way :
app.post('/init/autocomplete', function(req, res){
var autocomplete = {
companies: [],
offices: []
};
// Find all companies
Company.find({}, function(err, companies) {
if (err) throw err;
companies.forEach(function(company) {
autocomplete.companies.push({value: company.name})
});
// Find all offices
Office.find({}, function(err, offices) {
if (err) throw err;
offices.forEach(function(office) {
autocomplete.offices.push({value: office.name})
});
res.json(autocomplete);
});
});
});
But I don't know if it's the good way. Maybe using promise will be better ? I'm open for all suggestions.