title: when to use $q.defer() in Angularjs
body: <p>I am new to Angularjs and I m following this tutorial :<a href="http://mherman.org/blog/2015/07/02/handling-user-authentication-with-the-mean-stack/#.WE70iubhCM8" rel="nofollow noreferrer">http://mherman.org/blog/2015/07/02/handling-user-authentication-with-the-mean-stack/#.WE70iubhCM8</a> . However i dont understand when to use  $q.defer(). For example in the folllowing Angularjs code why use  $q.defer() :</p>
  
  <pre><code>function login(username, password) {
  
        // create a new instance of deferred
        var deferred = $q.defer();
  
        // send a post request to the server
        $http.post('/user/login',
          {username: username, password: password})
          // handle success
          .success(function (data, status) {
            if(status === 200 &amp;&amp; data.status){
              user = true;
              deferred.resolve();
            } else {
              user = false;
              deferred.reject();
            }
          })
          // handle error
          .error(function (data) {
            user = false;
            deferred.reject();
          });
  </code></pre>
  
  <p>The server side code is :</p>
  
  <pre><code>router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return res.status(401).json({
          err: info
        });
      }
      req.logIn(user, function(err) {
        if (err) {
          return res.status(500).json({
            err: 'Could not log in user'
          });
        }
        res.status(200).json({
          status: 'Login successful!'
        });
      });
    })(req, res, next);
  });
  </code></pre>
  
  <p>And why not use it in the following Angularjs code :</p>
  
  <pre><code> function getUserStatus() {
        return $http.get('/user/status')
        // handle success
        .success(function (data) {
          if(data.status){
            user = true;
          } else {
            user = false;
          }
        })
        // handle error
        .error(function (data) {
          user = false;
        });
      }
  </code></pre>
  
  <p>Server side code is :</p>
  
  <pre><code>router.get('/status', function(req, res) {
    if (!req.isAuthenticated()) {
      return res.status(200).json({
        status: false
      });
    }
    res.status(200).json({
      status: true
    });
  });
  </code></pre>