Angularjs inconsistent delays between $http.get and $http.post

82 Views Asked by At

Here is a part of the code of one of my controllers.

//service call to add record to database
//bookApi has addBook method which contains a $http.post inside

bookApi.addBook(book);

//service call to show list of all books
//bookApi has a getBooks method which contains $http.get call

bookApi.getBooks().then(function(response){
            $scope.booklist = response.data;
    },function(data,status,config,headers) {
        alert('some error occured');
    }); 

What happens is when booklist is displayed in the page sometimes the getBooks call finishes first before the addBook since they are both asynchronous. SO in the page, when a book is submitted in a Add book page, the next page that gets display is the list of books page which sometimes does not contain the newly added book first (you would need to refresh).

How can this be avoided?

1

There are 1 best solutions below

1
On BEST ANSWER

Chain the promises together in a flat manner like so:

bookApi.addBook(book).then(function() {
    return booksApi.getBooks();
}).then(function(response) {
    $scope.booklist = response.data;
}, function(data,status,config,headers) {
    alert('some error occured');
});

In order to combat callback hell, return getBooks in the callback. Typically, good promise methodology says you shouldn't chain then inside another then, but return the promise and continue the chain instead.