1

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!

Kiwanax
  • 1,265
  • 1
  • 22
  • 41

2 Answers2

3

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.

irfn
  • 560
  • 3
  • 11
  • 1
    jquery promises are described here http://api.jquery.com/promise/ and here http://api.jquery.com/jquery.getjson/ – irfn Jun 30 '14 at 04:40
  • 1
    jQuery's `.done` `.fail` `.always` etc are __nothing__ like Q's promises' `.then` or Angular's promises since they _don't chain_. Instead, you can compare it to jQuery's own `.then`. – Benjamin Gruenbaum Jun 30 '14 at 08:47
  • 1
    @BenjaminGruenbaum Agreed that Q and Angular promises are superior https://github.com/kriskowal/q/wiki/Coming-from-jQuery is a good article comparing them. I merely mentioned that jquery supports promise "style" and not that these are A+ promise compliant. – irfn Jul 01 '14 at 07:35
0

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.

Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84
  • Nice way using `$http` AngularJS object, but is there something like the `beforeSend` property as jQuery Ajax call has? – Kiwanax Jun 30 '14 at 10:26
  • http://stackoverflow.com/questions/22140591/what-is-the-equivalent-of-jquery-ajax-beforesend-in-angularjs gives you the answer to that. https://docs.angularjs.org/api/ng/service/$http has the documentation about it. I personally have no used `.interceptors` myself but it'd be interesting to learn about it! – Mohamed El Mahallawy Jun 30 '14 at 17:44