napfernandes
napfernandes

Reputation: 1359

Convert a simple ajax call to use promise jQuery/AngularJS

I have this general method to use AJAX calls in a app:

function doAjaxCommand(url, type, async, params, successCallback, failCallback) {
    $.ajax({
        url: url,
        type: type,
        async: async,
        dataType: "json",
        data: JSON.stringify(params)
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            if (result.Success) {
                successCallback(result);
            } else {
                if (failCallback !== undefined) {
                    failCallback(result);
                }
                return false;
            }
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
            console.log(xhr);
            console.log(status);
        }    
    });
}

I heard that using promises I can take a better use from async operations. However, I have no clue how to use promises. I've never used it, and I don't get the whole idea in some links I read about. Can you guys please give me a light about it? Even how to start thinking?

Any help would be apreciated, thank you!

Upvotes: 1

Views: 2738

Answers (2)

Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13842

I found this to be the best thing to explain Angularjs promises to me:

http://andyshora.com/promises-angularjs-explained-as-cartoon.html

If you plan on interacting with a backend regularly and restfully, I'd recommend Restangular

In angularjs, if you want to use the default $http, referencing Angular's docs:

 $http({method: 'GET', url: '/someUrl'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

This exposes the promise success and error Or you can do

 $http({method: 'GET', url: '/someUrl'}).
    then(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
      $scope.users = response.users;
    })

Which expose the then promise of when the aync is finished, then do something.

Upvotes: 0

irfn
irfn

Reputation: 560

Actually promises allow a better way to 'compose' callbacks. Regular callbacks usually result in a 'Pyramid of doom'.

    step1(function (value1) {
        step2(value1, function(value2) {
            step3(value2, function(value3) {
              step4(value3, function(value4) {
                // Do something with value4
              });
          });
        });
    });

Instead promises allow a flattened call flow. eg: using q.js(https://github.com/kriskowal/q) we can do

Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
    // Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();

jquery also supports the promise style

var jqxhr = $.getJSON( "example.json", function() {
     console.log( "success" );
})
.done(function() {
    console.log( "second success" );
})
.fail(function() {
    console.log( "error" );
})
.always(function() {
   console.log( "complete" );
});

However you should use the angular promises which is built in.

Upvotes: 3

Related Questions