Izzy
Izzy

Reputation: 412

Manually resolving AJAX return with promise

I tried to grasp my head around promises, and it looked simple. I imagined them as asynchronous vars. One of the problem I needed to resolve was making several AJAX calls which all needed to be resolved successfully, chaining them one after another, aka I need to make them synchronous to get the result. As making ajax call sync: false is deprecated I tried to make AJAX synchronous with promises.

     $.when(
          ajaxCall(param1),
          ajaxCall(param2)
     ).then(
        function(data) {
          console.log(['OK: ',data]);
        }, function() {
          console.log('Error');
        }
     ).fail(function () {
        console.log('Fail');
     });

And ajax call function is defined as:

ajaxCall: function ($id) {

        $.ajax({

             url: 'some_url'
             type: 'POST',
             dataType: "JSON",
             data: packed,

             success: function (data) {

                 var deferred = $.Deferred();
                 switch (data.code) {
                     case 200:
                         deferred.resolve(data);
                         break;
                     default:
                         deferred.reject(data);
                         break;
                 }

                 return deferred.promise();

             },
             error: function () {
                 $.Deferred().reject();
             }
         });

     }

I directly made some false ajax calls, but the .fail branch was never executed, and I am not sure what the problem is. If I change .then to .done, then at least Error callback is executed, but no mater what I tried, I never reached Fail branch.

Solution is probably simple, but looks like I am unable to properly formulate the question to find solution to my problem.

So I have tree questions:

  1. Why the .fail is never called, and what I need to change to make it work?
  2. I basically understand difference between .done and .then. Both are called when promise is resolved, only that .then is chainable while done is not (If I'm correct). .done and .fail are usually paired as both have one callback, and .then has two. As I used two callbacks in .done why is second one called, since all callbacks in done are success callbacks?
  3. Why reject doesn't call fail branch?

Any help is appreciated.

Upvotes: 1

Views: 7165

Answers (1)

Haresh Vidja
Haresh Vidja

Reputation: 8496

You can do something like below

var ajaxCall= function ($id) {
    return $.ajax({

        url: 'some_url'
        type: 'POST',
        dataType: "JSON",
        data: packed,

        success: function (data) {

            var deferred = $.Deferred();
            switch (data.code) {
                case 200:
                    deferred.resolve(data);
                break;
                default:
                    deferred.reject(data);
                break;
            }

            return deferred.promise();

        },
        error: function () {
            $.Deferred().reject();
        }
    });
};

var successCall= function(){
 // code after both request completed with success;

};

var failureCall= function(){
// code after both request completed and if have error

};

$.when(ajaxCall(param1),ajaxCall(param2))
  .then( successCall, myFailure );

I have not tested but I read this kind a code in jQuery document at end of description in Examples section https://api.jquery.com/jquery.when/

Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then(myFunc, myFailure );

Upvotes: 1

Related Questions