0

I'd like to set a variable from a function's return data, however, there is a $.post() call inside. How do i modify the following code to return the data. i've looked at a bunch of suggestions but none seem to work.

Currently the sData inside the .then() is a global variable, i'd like to use that as the return value so a local call anywhere of var thisData = getItemData(id, div); will be the same as the current global variable sData. I saw using a callback function but this doesn't solve the issue as i'd have to use the global variable inside that callback.

forgive the complex ternary, there are 3 possible JSON types that could be returned server side.

function getItemData(id, div) {
    typeof id !== 'undefined' ? id : '220';
    typeof div !== 'undefined' ? div : '';
    beginLoading(div);
    return $.post({
        url: '/content/itemsjson/?categoryid=' + id,
        data: { },
        async: false,
    })
    .done(function(data, status, request) {
        //***
    })
    .fail(function(xhr, textStatus, errorThrown) {
        //***
    })
    .always(function(data) {
        //***
    })
    .then(function(data) {
        stopLoading(div);
        sData = (typeof data == 'string') ? JSON.parse(data.responseText) : (data[0] ? data[0] : data);
    });
}
Viking NM
  • 392
  • 3
  • 17

1 Answers1

0

Using sync calls means that you will freeze the browser until getting the response. Instead of that you should use Deferred object :

function getItemData(id, div) {
    typeof id !== 'undefined' ? id : '220';
    typeof div !== 'undefined' ? div : '';
    beginLoading(div);
    var dfd = $.Deferred();
    $.post({
        url: '/content/itemsjson/?categoryid=' + id
    })
    .fail(function(xhr, textStatus, errorThrown) {
        dfd.reject(xhr);
    })
    .then(function(data) {
        stopLoading(div);
        sData = (typeof data == 'string') ? JSON.parse(data.responseText) : (data[0] ? data[0] : data);
        dfd.resolve(sData);
    });
    return dfd.promise();
}
  • that didn't seem to work, all i get back is the $.post() object prototype, the same thing i'm getting out of the one posted with the question – Viking NM Nov 14 '19 at 13:27
  • This function returns deferred promise and the actual return is in the resolve which is the data not the post function. – Meisam Mahdian Nov 14 '19 at 21:39