I am using angular resource modul to work with my restfull webserver. For exampe i have a method which returns an array of 10 elements and what i want to do is just save result into some javascript variable (not in angular scope) called books.
So i have written a simple method which looks like this:
function getBooks(user_id) {
var books = [];
BookFactory.getBooks.query({ id: user_id }).$promise.then(function (result) {
angular.forEach(result, function(i) {
books.push(i);
});
});
return books;
}
Let's assume that BookFactory.getBooks.query works as expected and truly returns 10 elements. So there is a simple logic inside this function, i just push each element to the array books.
Also i have a test function for testing getBooks() function. Here it is:
$scope.testGetBooksMethod = function (user_id) {
var resut = getBooks(user_id);
alert(resut.length);
};
The result in alert will be always 0. I know that this part of code:
BookFactory.getBooks.query({ id: user_id }).$promise.then(function (result) {
angular.forEach(result, function(i) {
books.push(i);
});
});
works asynchronously and until server request is processing, function getBooks() returns an empty array of books (please correct me if i am wrong).
Here is a question, how can i edit my function, to work it correctly. I want to get data from rest, fill the array books with this data and then return it.
Thanks in advance.