0

I have finally understood promise and implemented it and all ajax request that query the database is using it. Now i would like to display some kind of loading progress animation nothing to fancy.

According to MDN documentation found here

They state that a Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

I would like to know how i can take advantage of the pending state to display my animation.

Example of the Promise:

function functionName(param1,param2,...){
      return new Promise(function (resolve, reject) {

         $.ajax({
               // ajax param here
               success: function (data, status) {
                         resolve(data);
                         return;
                        },
                        error: function (xhr, desc, err) {
                        console.log(xhr);
                        console.log("Details: " + desc + "\nError:" + err);
                        return;
                        }
                });
       });
};

And a function that uses it;

$(document.body).on("event", "element", function (event) {
        event.preventDefault();
        var data = functionName(param1,param2,...).then(function (response) {
        data = response;
            // handeling data from Promise function
         }, function (error) {
        console.error("ERROR !", error);
        return;
        });

});

So I am wondering how we can take advantage of the pending state to display an animation?

MadeInDreams
  • 1,991
  • 5
  • 33
  • 64
  • 1
    http://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request – null1941 Jan 23 '16 at 07:31
  • https://github.com/likerRr/jq-ajax-progress – null1941 Jan 23 '16 at 07:32
  • All you need to do is to start the animation and then turn it off with a `then` on the promise. By the way, could you please indent your code properly? –  Jan 23 '16 at 11:37

1 Answers1

1

You can modify your code something like below

$(document.body).on("event", "element", function (event) {
    event.preventDefault();
    var data = functionName(param1,param2,...).then(function (response) {
    // End your animation here like hide progress bar        
    data = response;
    // handeling data from Promise function
}, function (error) {
    // End your animation here like hide progress bar        
    console.error("ERROR !", error);
    return;
});
// Start your animation here like show progress bar
Kyle Muir
  • 3,875
  • 2
  • 22
  • 27
Nitin Garg
  • 888
  • 6
  • 7