Joh*_*ohn 6 javascript mongoose mongodb node.js promise
我正在尝试使用此库初始化带有自动完成功能的两个输入.当我加载页面时,我将触发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({}, 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);
});
Run Code Online (Sandbox Code Playgroud)
我知道find方法是异步的.这就是为什么我按以下顺序看到我的console.log():
Three
One
Two
Run Code Online (Sandbox Code Playgroud)
如何完成并完成console.log('Three');时如何触发?Company.findOffice.find
我想看看console.log('Three');最后一个位置.
编辑:
我想我可以这样做:
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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
但我不知道这是不是好方法.也许使用诺言会更好?我愿意接受所有建议.
Mongoose 内置了对 promises 的支持,它提供了一种干净的方式来等待多个异步查询操作的完成Promise.all:
// Tell Mongoose to use the native Node.js promise library.
mongoose.Promise = global.Promise;
app.post('/init/autocomplete', function(req, res){
var autocomplete = {
companies: [],
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.
});
});
Run Code Online (Sandbox Code Playgroud)