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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Excelent answer, very helpful +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.