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 PostsService.getPostBySlug to return the desired post?
Posts service
Website.factory( 'PostsService',
[ '$filter', '$http', function( filter, $http )
{
// declare service
var PostsService = {};
Return all posts (reads posts.json)
PostsService.getPosts = function( callback )
{
$http
.get( 'posts/posts.json' )
.success( callback );
}
Return one post based on its slug
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;
}
Return service
// return service
return PostsService;
}]);
The output is
null BlogController.js:26
undefined BlogController.js:51
[Object, Object] BlogController.js:33
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.