Node.js检测两个猫鼬查找何时完成 [英] Node.js detect when two mongoose find are finished

查看:70
本文介绍了Node.js检测两个猫鼬查找何时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用使用自动完成功能初始化两个输入.加载页面时,我将触发Ajax来初始化两个输入文本.

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);
});

我知道find方法是异步的.这就是为什么我按此顺序看到console.log()的原因:

I know than the find method is async. That is why I see my console.log() in this order :

Three
One
Two

Company.findOffice.find完成后,如何触发console.log('Three');?

How can I do to trigger console.log('Three'); when the Company.find and Office.find are finished ?

我想在最后一个位置看到console.log('Three');.

I want to see the console.log('Three'); at the last position.

我想我可以这样:

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.

推荐答案

Mongoose具有对Promise的内置支持,该支持提供了一种干净的方式来等待使用

Mongoose has built-in support for promises which provide a clean way to wait for the completion of multiple async query operations with 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.
        });
});

这篇关于Node.js检测两个猫鼬查找何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆