函数返回全局变量

时间:2021-03-26 00:41:33

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.

我想在getCurrentUser函数中设置currentUserId,我想在其他函数中调用它。

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

2 个解决方案

#1


2  

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.

之所以会出现这种情况,是因为在getCurrentUser方法中,您正在执行一个异步AJAX调用,所以在使用console.log打印时还没有准备好这个值。

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

当GET /set_user请求成功结束时,值将被正确设置,只有在这种情况下,函数:

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

will be executed and currentUserId will be set.

将执行并设置currentUserId。

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

基于jQuery.ajax()文档,返回的值为$。ajax调用是一个承诺。首先,将承诺返回给调用者(1),然后等待承诺被解析为打印值(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);    
});

#2


1  

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

与Andrea explain一样,在进行ajax调用时,值还没有准备好。

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.

这也将避免使用globe变量currentUserId。

#1


2  

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.

之所以会出现这种情况,是因为在getCurrentUser方法中,您正在执行一个异步AJAX调用,所以在使用console.log打印时还没有准备好这个值。

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

当GET /set_user请求成功结束时,值将被正确设置,只有在这种情况下,函数:

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

will be executed and currentUserId will be set.

将执行并设置currentUserId。

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

基于jQuery.ajax()文档,返回的值为$。ajax调用是一个承诺。首先,将承诺返回给调用者(1),然后等待承诺被解析为打印值(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);    
});

#2


1  

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

与Andrea explain一样,在进行ajax调用时,值还没有准备好。

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.

这也将避免使用globe变量currentUserId。