我正在尝试使用此
library使用自动完成初始化两个输入.当我加载页面时,我将触发Ajax来初始化两个输入文本.
但我不知道当我的猫鼬发现完成时我怎么能发现.
这是我的服务器端代码:
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({},offices) { if (err) throw err; offices.forEach(function(office) { autocomplete.offices.push({value: office.name}) }); console.log('Two'); }); console.log('Three'); // res.json(autocomplete); });
我知道find方法是异步的.这就是为什么我按以下顺序看到我的console.log():
Three One Two
如何触发console.log(‘Three’);当Company.find和Office.find完成后?
我想看看console.log(‘Three’);在最后一个位置.
编辑:
我想我可以这样做:
app.post('/init/autocomplete',companies) { if (err) throw err; companies.forEach(function(company) { autocomplete.companies.push({value: company.name}) }); // Find all offices Office.find({},offices) { if (err) throw err; offices.forEach(function(office) { autocomplete.offices.push({value: office.name}) }); res.json(autocomplete); }); }); });
但我不知道这是不是好方法.也许使用诺言会更好?我愿意接受所有建议.
解决方法
Mongoose内置了对promises的支持,它提供了一种等待用
Promise.all
完成多个异步查询操作的简洁方法:
// Tell Mongoose to use the native Node.js promise library. mongoose.Promise = global.Promise; app.post('/init/autocomplete',offices: [] }; // Call .exec() on each query without a callback to return its promise. Promise.all([Company.find({}).exec(),Office.find({}).exec()]) .then(results => { // results is an array of the results of each promise,in order. autocomplete.companies = results[0].map(c => ({value: c.name})); autocomplete.offices = results[1].map(o => ({value: o.name})); res.json(autocomplete); }) .catch(err => { throw err; // res.sendStatus(500) might be better here. }); });