0

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');
    }
});

1 Answer 1

2

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');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answser. It works perfectly. I don't know we can return User.findOne(). It's possible to write just one return res.redirect('/login'); ? I did and it works but maybe this will give an error in certain case ?
Oh, sure, you can remove the first one. I'll adjust my example. It won't give any problems.

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.