我需要检索来自外部API的数据。返回的数据为JSON格式,我可以很好地读取它。问题是,我正在调用一个函数,然后该函数获取用户名。然后,我想将该用户名返回给调用函数,但是无论我尝试什么,我总会得到一个“未定义”的值。
如果我在RETURN之前在控制台中显示用户名,则可以看到该值而不会出现问题,但是变量的返回似乎不起作用。
还有更多代码,但这是我似乎无法正确理解的部分(请注意,我在代码中也留下了注释):
var myName = '';
myName = GetSender(mySenderID); // this is called from another JS function, mySenderID does have a value
console.log(myName); // show "undefined"
function GetSender(SenderID)
{
var data = JSON.stringify(false);
var mySenderName = "";
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
response = JSON.parse(this.responseText);
mySenderName = response.user.first_name + " " + response.user.last_name;
console.log(mySenderName); // this shows a value
return mySenderName; // This part does not return anything to the calling function
}
});
xhr.open("GET", "https://blah.com/" + SenderID);
xhr.setRequestHeader("X-Public-Token", "78fc204914f6a1231a34c456ff487fa6");
xhr.setRequestHeader("accept", "application/json; version=1");
xhr.send(data);
}