E
E
Egor Mikheev2016-12-20 18:23:06
JavaScript
Egor Mikheev, 2016-12-20 18:23:06

How to use functions passed to a method?

Hello, I'm studying the material from the book, but I can't understand how this code works.
a function and its method are created here

function NewsletterSignup(){
    
}
NewsletterSignup.prototype.save = function(cb){
   cb();
};

app.post('/newsletter', function(req, res){
  var name = req.body.name || '', email = req.body.email || '';
  // input validation
  if(!email.match(VALID_EMAIL_REGEX)) {
    if(req.xhr) return res.json({ error: 'Invalid name email address.' });
    req.session.flash = {
      type: 'danger',
      intro: 'Validation error!',
      message: 'The email address you entered was  not valid.',
    };
    return res.redirect(303, '/newsletter/archive');
  }
  new NewsletterSignup({ name: name, email: email }).save(function(err){
    if(err) {
      if(req.xhr) return res.json({ error: 'Database error.' });
      req.session.flash = {
        type: 'danger',
        intro: 'Database error!',
        message: 'There was a database error; please try again later.',
      };
      return res.redirect(303, '/newsletter/archive');
    }
    if(req.xhr) return res.json({ success: true });
    req.session.flash = {
      type: 'success',
      intro: 'Thank you!',
      message: 'You have now been signed up for the newsletter.',
    };
    return res.redirect(303, '/newsletter/archive');
  });
});

I can not understand this part of the code, when the err object appears, and how to implement it in this example?
new NewsletterSignup({ name: name, email: email }).save(function(err){
    if(err) { // в каком случае сюда попадет?
      if(req.xhr) return res.json({ error: 'Database error.' });
      req.session.flash = {
        type: 'danger',
        intro: 'Database error!',
        message: 'There was a database error; please try again later.',
      };
      return res.redirect(303, '/newsletter/archive');
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2016-12-20
@ogregor

Apparently at this stage the code is:

NewsletterSignup.prototype.save = function(cb){
   cb();
};

until it is simply added, in the future there will be a real call to the server and if an error returns, then cb () will be called with the argument cb (err) and then your callback function will receive a variable with an error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question