Reputation: 6159
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
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 $.ajax
call 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
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 todeferred.then()
for implementation details.
Upvotes: 2