gwalshington
gwalshington

Reputation: 1495

Function to return a global variable

I feel like this is really easy, but I can not figure it out.

I want to set the currentUserId inside of the getCurrentUser function, which I would like to be able to call inside other functions.

Below is what I have now, and it returns undefined. What am I missing?

var currentUserId;

function getCurrentUser()   {
    $.ajax({
        type: "GET",
        url: '/set_user',
        success: function(result)   {
            currentUserId = result.id;
            return currentUserId;
        },
        error: function(err)    {
            console.log(err);
        }

    })
};

getCurrentUser();
console.log("current user id is " + currentUserId);    

Upvotes: 1

Views: 73

Answers (2)

Charles Guo
Charles Guo

Reputation: 170

Like Andrea explain, the value was not ready yet when you make a ajax call.

One way to avoid this is use callback:

function getCurrentUser(callback)   {
    $.ajax({
        type: "GET",
        url: '/set_user',
        success: function(result)   {
            var currentUserId = result.id;
            if (callback)
              callback(currentUserId);
        },
        error: function(err)    {
            console.log(err);
        }

    })
};

function displayResult(userId){
  console.log("current user id is " + userId);   
}

getCurrentUser(displayResult);

And this will also avoid the use of globe variable currentUserId.

Upvotes: 2

Andrea
Andrea

Reputation: 3440

This happens because inside getCurrentUser method you are doing an asynchronous AJAX call, so the value is not yet ready when you print it with console.log.

The value will be correctly set when the GET /set_user request will end successfully, only in that case the function:

    success: function(result)   {
        currentUserId = result.id;
        return currentUserId;
    }

will be executed and currentUserId will be set.

Based on jQuery.ajax() documentation, the value returned by $.ajax call is a Promise. So first, return the promise to the caller (1) and then wait the promise is resolved to print the value (2).

var currentUserId;

function getCurrentUser()   {
    return $.ajax({ // 1. Return the Promise here
        type: "GET",
        url: '/set_user',
        success: function(result)   {
            currentUserId = result.id;
            return currentUserId;
        },
        error: function(err)    {
            console.log(err);
        }

    })
};

// 2. Then wait the call to succeed before print the value (use the 'done' method)
getCurrentUser().done(function() {
  console.log("current user id is " + currentUserId);    
});

Upvotes: 2

Related Questions