gwalshington gwalshington - 1 month ago 10
Ajax Question

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);

Answer

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);    
});
Comments