0

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?

2
  • You'd have to chain the get call to the post, otherwise it will treat them both as async in no order. You need to make sure the post finished before doing the get Commented Jan 5, 2017 at 7:12
  • getBooks should be call after completion of bookApi.addBook(book) call using chaining.. Commented Jan 5, 2017 at 7:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The rejection handler in a .then method receives an errorResponse object, not a spread of four arguments (data, status,...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.