John
John

Reputation: 4981

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

Upvotes: 0

Views: 62

Answers (1)

Daniel Diekmeier
Daniel Diekmeier

Reputation: 3434

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

Upvotes: 2

Related Questions