title: Filtering data from callback function
body: <p>When using AngularJS, I keep running into the problem of how to deal with the asynchronous behaviour and callback functions. In the below, how can I modify <code>PostsService.getPostBySlug</code> to return the desired post?</p>
  
  <p><strong>Posts service</strong></p>
  
  <pre><code>Website.factory( 'PostsService', 
  [ '$filter', '$http', function( filter, $http ) 
  {
      // declare service
      var PostsService = {};
  </code></pre>
  
  <p><strong>Return all posts (reads posts.json)</strong></p>
  
  <pre><code>    PostsService.getPosts = function( callback )
      {
          $http
              .get( 'posts/posts.json' )
              .success( callback );
      }
  </code></pre>
  
  <p><strong>Return one post based on its slug</strong></p>
  
  <pre><code>    PostsService.getPostBySlug = function( slug, callback )
      {
          // declare post
          var postForSlug = null;
          console.log( postForSlug ); // prints 'null'
  
          // get all posts from service
          var posts = PostsService.getPosts( function( data )
          {
              // all posts
              var posts = data;
              console.log( posts ); // prints array of objects
  
              // return all posts
              return posts;
          });
  
          // filter by slug
          postForSlug = filter( 'filter' )
          ( 
              posts,
              { 
                  'slug': slug
              } 
          );  
  
          console.log( postForSlug ); // prints 'undefined'
  
          // return post for the given slug
          return postForSlug;
      }
  </code></pre>
  
  <p><strong>Return service</strong></p>
  
  <pre><code>    // return service
      return PostsService;
  
  }]);    
  </code></pre>
  
  <hr>
  
  <p>The output is</p>
  
  <pre><code>null BlogController.js:26
  undefined BlogController.js:51
  [Object, Object] BlogController.js:33
  </code></pre>
  
  <p>which goes to show that the order of execution is different from what I expected. I know that it is about the asynchronous behaviour and the callback function, but I don't really know how to fix it. I keep running into this problem and it would be very much appreciated if someone could show me how to deal with this type of situation.</p>