如何在node.js中编写可重用的函数?

时间:2015-10-27 07:20:11

标签: node.js

我想重用findemail函数

    function findemail(val){
        user.findOne({ email : val }, function (err, person) {
         if(err) throw err;
         if(person == null){
           console.log(false+"1");
           return false;
         }else{
           console.log(true+"1");
           return true;
         }
       });
     }

   router.post('/avail', function(req, res, next){
        \\somecodes
        var email = \\something
        console.log(findemail(email));
        res.send(findemail(email));
   });

输出cmd:

   undefined
   true1

我是初学者。任何人都可以帮助我吗?

findone是一种猫鼬方法

1 个答案:

答案 0 :(得分:1)

好的,我建议你阅读其他引用的问题,以便更好地理解异步问题。这是您的代码的解决方案:

  function findemail(val, fn){
        user.findOne({ email : val }, function (err, person) {
            if (err) return fn(false);
            fn(person != null);
       });
   }

   router.post('/avail', function(req, res, next){
        \\somecodes
        var email = \\something
        findemail(email, function(result) {
            res.send(result);
        });
   });

有关从异步操作返回值的更多详细信息,请参阅以下参考:

How do I return the response from an asynchronous call?

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Node.JS How to set a variable outside the current scope

Order of execution issue javascript

async.js and series issue