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!

4
  • add return before $.ajax(. that's it. Commented Jun 30, 2014 at 2:53
  • try reading this, it talks about how to use the $q library: docs.angularjs.org/api/ng/service/$q Commented Jun 30, 2014 at 3:01
  • 2
    You almost certainly should not be using jQuery with Angular. Use Angular's $http service. Commented Jun 30, 2014 at 4:00
  • Eh... just put a return before the $.ajax` it already uses promises, you just hook on them with .then. Also, what m59 said. Commented Jun 30, 2014 at 8:47

2 Answers 2

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.

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

3 Comments

jquery promises are described here api.jquery.com/promise and here api.jquery.com/jquery.getjson
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.
@BenjaminGruenbaum Agreed that Q and Angular promises are superior 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.
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.

2 Comments

Nice way using $http AngularJS object, but is there something like the beforeSend property as jQuery Ajax call has?
stackoverflow.com/questions/22140591/… gives you the answer to that. 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!

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.