在Nodejs中,如何等待进程直到从函数返回响应

时间:2017-08-24 06:58:10

标签: node.js express mailgun

我是Nodejs的新手。进程不会等到功能响应。因为Nodejs的异步调用。如何制作同步。请帮我。

这是我的代码

module.exports.signup = function(req, res){
console.log('signup');
User.findOne({'emails.email' : req.body.email}, function(err, doc) {
if (doc === null) {
var vr_token= genRandomString(16);
var ex_date = Date.now();
  var user = new User();
      user.emails.push({
        email : req.body.email,
        email_verification_token : vr_token,
        verify_key_expire : ex_date });
        user.save(function(err2,user1) {
          if (!err2) {
          var result = send_email.sync(vr_token);//process not waiting
            if(result) {
              res.json ({
                status: 200,
                message:"mail sent successfully",
                data:user1
              })
            }
          } 
       });
     }
  })      
}

这是我的功能

function send_email(vr_token){
var mailOpts = {
from: process.env.Mail_From_Addr,
to: 'xxxxxxxxxxxxx',
subject: 'Verify Your New Account Email',
html:'<p>Hello,</p>code : '+vr_token
 };
   mailgun.messages().send(mailOpts, function (err, response){
    if (!err){
    return true;
     }else{
     return false;
     }
  })
}

1 个答案:

答案 0 :(得分:0)

添加回调:

function send_email(vr_token, callback){
  var mailOpts = {
  from: process.env.Mail_From_Addr,
  to: 'xxxxxxxxxxxxx',
  subject: 'Verify Your New Account Email',
  html:'<p>Hello,</p>code : '+vr_token
  };
  mailgun.messages().send(mailOpts, function (err, response){
    callback(null, !err);
  })
}

守则:

module.exports.signup = function(req, res){
console.log('signup');
User.findOne({'emails.email' : req.body.email}, function(err, doc) {
if (doc === null) {
var vr_token= genRandomString(16);
var ex_date = Date.now();
  var user = new User();
      user.emails.push({
        email : req.body.email,
        email_verification_token : vr_token,
        verify_key_expire : ex_date });
        user.save(function(err2,user1) {
          if (!err2) {
            send_email.sync(vr_token, function(err, result){
              if(result) {
                res.json ({
                  status: 200,
                  message:"mail sent successfully",
                  data:user1
                })
              }
            });

          } 
      });
    }
  })      
}