I've read just about every post on Stack Overflow and elsewhere regarding this issue, but nothing seems to work. I need to retrieve a user's credits before they're allowed to make a purchase. Everything seemed to be working until earlier. Here's the code I thought was working:
function getCredits() {
return $.getJSON('users/getCredits').done(function(resp) {
return parseInt(resp.credits);
});
}
When I found this wasn't working as expected I tried setting an outer variable which .done() would modify.
function getCredits() {
var active_credits;
$.getJSON('users/getCredits'))
.done(function(resp) {
active_credits = parseInt(resp.credits);
});
return active_credits;
}
I've also tried playing around with .when() and .then() methods, which I have little familiarity with.
function getCredits() {
$.when($.getJSON('users/getCredits'))
.then(function(resp) {
active_credits = parseInt(resp.credits);
});
}
The only thing I've found to work is using $.ajax() with the async option set to false. But with that I get a deprecation warning, plus I've read several posts warning of this being bad practice.
Any help with this would be appreciated. My assumption about .done() has always been it waits until the HTTP request is finished processing.
UPDATE
So here's my latest attempt. I'm passing in a callback as has been suggested in this post as well as other posts. But I'm still getting an undefined message when trying to read the method's return value. I'm not sure what I'm doing wrong.
function getCredits() {
var active_credits;
function requestCredits(callback) {
$.getJSON('users/getCredits', callback).done(function(resp) {
callback(resp);
});
}
requestCredits(function(resp) {
active_credits = parseInt(resp.credits);
});
return active_credits;
}
I've also tried returning the value returned by the callback.. with no luck.
function getCredits() {
var active_credits;
function requestCredits(callback) {
$.getJSON('users/getCredits', callback).done(function(resp) {
callback(resp);
});
}
return requestCredits(function(resp) {
return parseInt(resp.credits);
});
}