0

I have this function:

GetMessage: function (code) {
            var msg = localStorage.getItem(code);
            if (msg == null || msg == 'undefined') {
                $.ajax({
                    type: 'GET',
                    url: CTHelper.ApiUrl() + '/Api/Case/GetMessage?code=' + code,
                    async : false,
                    success: function (result) {
                        localStorage.setItem(code, result);
                        return result;
                    },
                    error: function (result) {
                        return '';
                    }
                });
            }
            else {
                return msg;
            }
        },

The first time it is invoked, it goes to the server ($.ajax) and stores a value in the localStorage, so the second and so on invocations get the value from the cache/storage.

Now, it works well all the times but the first invocation, it seems like return result in the success function returns always undefined.

I thought setting the async : false would fix the issue but it didn't

Below an image that illustrates my problem

enter image description here

Victor Hugo Terceros
  • 2,969
  • 3
  • 18
  • 31

1 Answers1

4

The return statements inside the 2 callback functions success and error don't return your GetMessage function - they return from the callbacks. If you want your function to return the correct message, assign the result to msg and always return it at the end of GetMessage:

GetMessage: function(code) {
  var msg = localStorage.getItem(code);
  if (msg == null || msg == 'undefined') {
    $.ajax({
      type: 'GET',
      url: CTHelper.ApiUrl() + '/Api/Case/GetMessage?code=' + code,
      async: false,
      success: function(result) {
        localStorage.setItem(code, result);
        msg = result;
      },
      error: function(result) {
        msg = '';
      }
    });
  }

  return msg;
},

See the result below

enter image description here

Victor Hugo Terceros
  • 2,969
  • 3
  • 18
  • 31
AVAVT
  • 7,058
  • 2
  • 21
  • 44