1

What's the proper way to use custom callbacks with express.js functions?

Here's an example:

//routes/reset.js

user.save(function(err){
  if ( err ) return next(err);
  reset.send_reset_email(req, res, user, function(req, res){
    req.flash('info', 'Check your email for a link to reset your password.');
    res.redirect('/');
  });
});

What signature should I use for reset.send_reset_email for this to work correctly?

This is what I have:

exports.send_reset_email = function(req, res, user, next){
  //send email
  transport.sendMail(options, function(err, responseStatus) {
     if (err) { 
      console.log(err);
    } else { 
      next(req, res);
     //do I need to explicitly pass req, res here?
     //is next() reserved word here?
    } 
  });

});

Do I need to explicitly pass req, res here? is next() reserved word here?

1 Answer 1

2

next() accepts an error or another route and is usualy called to continue with the next middleware.

in your send_reset_email function your next() isn't express's next() because you pass in function(req,res) and not next, pass in your own callback instead to handle the outcome of your sendmail function.

user.save(function(err){
  if (err) return next(err) // if thats express's next()
  reset.send_reset_email(req, res, user, function(err, data){
    if(err) {
      // send err msg
    } else {
      req.flash('info', 'Check your email for a link to reset your password.');
      res.redirect('/');
    }
  });
});


xports.send_reset_email = function(req, res, user, cb){
  //send email
  transport.sendMail(options, function(err, responseStatus) {
     if (err) return cb(err)
     cb(null,responseStatus)
  })
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.