0

I have a JS object, in a property I use a function expression, within a variable result.

I need to populate the result variable and return it when processData has been invoketed.

Could you tell me what I'm doing wrong here, if you brief explain the problem and add a pieec of good would be great.

$(document).ready(function () {

    // General Settings
    var 
    ApiSettings = {
        clientId: 'aaa',
        clientSecret: 'bbb'
    }

    ApiSettings.uriGetToken = 'https://ccc.com/oauth/token?grant_type=client_credentials&client_id=' + encodeURIComponent(ApiSettings.clientId) + '&client_secret=' + encodeURIComponent(ApiSettings.clientSecret);

    ApiSettings.token = (function () {
        var result; // I'm not able to set this variable
        // Make an Ajax Request
        $.getJSON(ApiSettings.uriGetToken, processData);
        function processData(data) {
            result = data.access_token;
        }
        return result;
    })();

    console.log(ApiSettings);
    console.log(ApiSettings.uriGetToken);
    console.log('FINAL:' + ApiSettings.token);
});
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • quentin, thanks, but I believe it is not a duplicate as I have a problem with a variable and not with the AJAX response. let em know your thougs – GibboK Nov 09 '12 at 11:53
  • 1
    It is a duplicate. If it's a little hard to parse for you, what it's saying is that you can't really do what you're trying to do; that's now how Javascript works. You need to pass in a callback to your anonymous function - another inner function meant to be called when you receive your result in processData. That's where you should continue with any more work you need to do, not when you return from the function calling $.getJSON – jonvuri Nov 09 '12 at 11:54
  • the thing is ajax is async, so even though you call the function on creation, result will not be populated until after the ajax call will return. – Ohad Milchgrub Nov 09 '12 at 11:55

1 Answers1

3

You are actually able to set the result variable with your code. The problem is that you use .getJSON() which is an asynchronous method. You will fire away the Ajax request, your JavaScript will then go straight to the return method and return the result, before the server have had a chance to respond. Thus, you are returning from your function before you've had time to update the result.

Asynchronous methods can be a bit hard to grasp initially, especially if you are a beginner. What you have to do is either to restructure your code, so that you don't fetch the value with the same method you use to read the value.

Another options would be to use a synchronous Ajax request instead, forcing your JavaScript to wait for the server to respond before you return your result. This is rarely a good idea though, as your UI will be unresponsive until the server returns.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103