Alex
Alex

Reputation: 6159

Async AJAX call not working with when and then

I have the following code:

function accessControl(userId) {
    return $.ajax({
        url: "userwidgets",
        type: "get",
        dataType: 'json',
        data: {
            userid: userId
        }
    });
};

var userWidgets = accessControl('1');
$.when(userWidgets).then(function (data) {
    alert(data);
});

I don't want to make the function sync by adding the parameter async: false, but the alert isn't appearing at all, is there something wrong in my code? should I use another approach?

Upvotes: 3

Views: 209

Answers (2)

Anish Patel
Anish Patel

Reputation: 4402

I don't want to make the function sync by adding the parameter async: false, but the alert isn't appearing at all, is there something wrong in my code? should I use another approach?

Making the ajax call synchronous will not solve this problem. Your approach is fine.

As @Tushar has said in his answer you don't really need to use $.when since the $.ajaxcall returns a promise so you can chain .then callbacks onto it without using $.when. But this is not the reason why your .then callback is not being invoked.

The reason why your .then callback is not being called is because that ajax call is failing and the promise is being rejected. .then callbacks are only called when promises are resolved successfully, this fiddle verifies this statement.

You will need add failure logic to your code to handle failures in your ajax call like this:

var userWidgets = accessControl('1');
$.when(userWidgets).then(function (data) {
    alert(data);
})
.fail(function(){
   alert("should do something on failure");
});

Upvotes: 1

Tushar
Tushar

Reputation: 87233

$.ajax returns a promise. So, it don't need to be wrapped in $.when again.

Use then directly on userWidgets as it is ajax instance.

userWidgets.then(function (data) {
    alert(data);
}, function(e, status, error) {
    console.log(error);
    // For debugging
});

From jQuery Docs

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Upvotes: 2

Related Questions