NodeJS异步数据库获取服务器冻结

时间:2018-06-13 13:26:28

标签: javascript node.js express asynchronous

我有一个在NodeJS上运行的应用程序(express + mongoose + jade)。 我有一个路由后 / search (所有路由都在一个单独的模块中),它应该处理从mongo数据库中获取数据并将其插入到jade模板中(在这种情况下只是打印控制台):

router.post('/search', function (req,res) {

    var componentsArray = null;

    function getArray(){
        console.log('Initializing...');
        componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
    }
    getArray(function () {
        console.log('Documents returned.');
        console.log('Printing array...');
        console.log('Array: ' + componentsArray);
        console.log('Array type: ' + typeof (componentsArray));
        console.log('Rendering page...');
        res.render('search_results');
    });
});

搜索和获取在不同模块中实现的功能 dataExchanger

exports.search = function(select, type, data) {
    console.log('Fetching documents...');
    componentsModel.find({name: data}, function (err, docs) {
        if(!err) {
            console.log('Returning documents...');
            return docs;
        } else {
            console.log('Can\'t return documents!');
            throw err;
        }
    });

};

问题当我使用 getArray()的回调函数时,服务器只是在返回文档时冻结并停止响应。 我做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试使用async / await

router.post('/search', async (req,res) => {
  let componentsArray;

  try {
     componentsArray = await dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
  } catch(e){
    //If error in request and no data.
    console.error('Error', e.message);
    return res.render('error_message');
  }

  console.log('Documents returned.');
  console.log('Printing array...');
  console.log('Array: ' + componentsArray);
  console.log('Array type: ' + typeof (componentsArray));
  console.log('Rendering page...');

  res.render('search_results');

});

这是您的dataExchanger

exports.search = function(select, type, data) {
   console.log('Fetching documents...');

   return new Promise((resolve, reject) => {
     componentsModel.find({name: data}, function (err, docs) {
       if(err) return reject(err);
       resolve(docs);
      });
   })
};

进一步阅读:promisesasync/await

答案 1 :(得分:0)

    router.post('/search', function (req,res) {

        var componentsArray = null;

        function getArray(cb){
            console.log('Initializing...');
            componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
//Execute the callback    
cb();
        }
        getArray(function () {
            console.log('Documents returned.');
            console.log('Printing array...');
            console.log('Array: ' + componentsArray);
            console.log('Array type: ' + typeof (componentsArray));
            console.log('Rendering page...');
            res.render('search_results');
        });
    });

您的搜索方法看起来也是异步的,因此您需要将回调传递给它以获得所需的结果。