John John - 3 months ago 6
Node.js Question

Node js avoid else if when callback is used

I have 2 if. The first I'm checking if the get parameters exists. The second I'm checking if param1 == param2 and inside this condition I'll find a user and I redirect inside the callback.

But I must set else for the other case bacause I'll get :

Error: Can't set headers after they are sent.


Is there a way to not write the else condition in my case ? For example wait when the find callback is finished then I can execute a redirect.

app.get('/path', function(req, res){

if( typeof req.param('param1') != 'undefined' && typeof req.param('param2') != 'undefined){

var param1 = req.param('param1');
var param2 = req.param('param2');

if ( param1 === param2 ){

// Confirm the user
User.findOne({ 'myfield' : param1 }, function(err, user) {
if (err) throw err;

if ( user.myfield == 'something' ){
return res.redirect('/login');
}

// Check if user already exists
if (user){
user.field2 = 'anything';
// Update user status
user.save(function(err){
if(err) throw err;

return res.redirect('/register');
});
}
});
}else{
return res.redirect('/login');
}
}else{
return res.redirect('/login');
}
});

Answer

Sure, you can just avoid the else clauses if you explicitly return every time:

app.get('/path', function(req, res) {
  if (typeof req.param('param1') !== 'undefined' && typeof req.param('param2') !== 'undefined'){

    var param1 = req.param('param1');
    var param2 = req.param('param2');

    if (param1 === param2) {
      // explicitly return
      return User.findOne({ 'myfield' : param1 }, function (err, user) {
        // Do some async stuff, doesn't matter
      })
    }
  }

  return res.redirect('/login');
});
Comments