如何在Node.js

时间:2016-09-21 11:24:26

标签: node.js express

我想调用其他函数以及如何获取该函数的结果,

功能1,

  exports.getprofiledatalistbyid = function (req, res) {
  var params = req.params;
  var profile= db.collection('profile');
  var requests= db.collection('requests');
  profile.find().toArray((err, result) => {
   if (err){ return console.log(err)
    }
      if(result){
                  //  console.log(result)
                   for(var i in result){
                     var id = result[i]._id;
                     var id = id.toString();
                   exports.getdetails(id)
                   }
                 }
        else{
            response = {status:'fail',data:[] };
        }
      // res.send(response);

  });
};

函数2,

exports.getdetails = function (req,res) {
  // var profile= db.collection('profile');
  var requests= db.collection('requests');
  var params = req.params;
  var id = params.id;
  requests.find( { $or:[ {'sent_id':id}, {'recieved_id':id}]}).toArray((err, result) => {
   if (err){ return console.log(err)
    }
      if(result){console.log(result)
           return result;
                 }
        else{
            response = {status:'fail',data:[] };
        }

  });
};

路线,

    var profile = require('../controller/user');
 router.get('/getprofiledatalistbyid/:id?', cors(), profile.getprofiledatalistbyid);

所以这里我想在函数1中使用函数2的结果。

有人可以帮助我吗?

感谢。

1 个答案:

答案 0 :(得分:1)

  

使用module.exports并通过functions

致电this
      module.exports = {
  getprofiledatalistbyid: function(req, res) {
    var params = req.params;
    var profile = db.collection('profile');
    var requests = db.collection('requests');
    profile.find().toArray((err, result) => {
      if (err) {
        return console.log(err)
      }
      if (result) {
        //  console.log(result)
        for (var i in result) {
          var id = result[i]._id;
          var id = id.toString();
           this.getdetails(req,res,function(err,result){
              if(!err)
            console.log(result);
           }); 
        }
      } else {
        response = {
          status: 'fail',
          data: []
        };
      }
      // res.send(response);

    });
  },

  getdetails: function(req, res,callback) {
    // var profile= db.collection('profile');
    var requests = db.collection('requests');
    var params = req.params;
    var id = params.id;
    requests.find({
      $or: [{
        'sent_id': id
      }, {
        'recieved_id': id
      }]
    }).toArray((err, result) => {
      if (err) {
        return callback(err)
      }
      if (result) {
        console.log(result)
        return callback(null,result);
      } else {
        callback(null, {
          status: 'fail',
          data: []
        });
      }

    });
  }
};