This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 31 answers
如何从异步调用返回响应? 31个答案
function getUsername() {
$.get("http://www.roblox.com/mobileapi/userinfo", function(data) {
return data.UserName;
});
}
console.log(getUsername());
It says "undefined" but whenever I visit the link manually it shows
它说“未定义”,但每当我手动访问该链接时,它会显示
{"UserID":74798521,"UserName":"AbstractMadness","RobuxBalance":7024,"TicketsBalance":21530,"ThumbnailUrl":"http://t2.rbxcdn.com/c189198f6c0689ce004d9438c70eb1bb","IsAnyBuildersClubMember":true}
It will also log the name if I do console.log(data.UserName) inside of the function.
如果我在函数内部执行console.log(data.UserName),它也会记录名称。
2 个解决方案
#1
0
It's not synchronous. You are printing the return of that function, which doesn't return anything (so it's undefined). Even if you were to return the $.get
call you wouldn't get what you're looking for. You need to log inside of the callback function or use a promise.
这不是同步的。您正在打印该函数的返回,该函数不返回任何内容(因此未定义)。即使你要退回$ .get电话,你也不会得到你想要的东西。您需要登录回调函数或使用promise。
function getUsername() {
return $.get("http://www.roblox.com/mobileapi/userinfo", function(data) {
console.log(data.UserName);
return data.UserName;
});
}
getUsername().done(function(username) { console.log(username); });
#2
0
Function getUsername
executes a $.get
request, but it returns nothing and it ends here.
函数getUsername执行$ .getrequest,但它不返回任何内容,它在此处结束。
You have to log your data in the function of your asynchronous $.get
request. This function (function(data)) is a callback function. It will be called, if the response of your $.get
request arrive.
您必须在异步$ .get请求的函数中记录您的数据。该函数(函数(数据))是一个回调函数。如果您的$ .get请求的响应到达,它将被调用。
#1
0
It's not synchronous. You are printing the return of that function, which doesn't return anything (so it's undefined). Even if you were to return the $.get
call you wouldn't get what you're looking for. You need to log inside of the callback function or use a promise.
这不是同步的。您正在打印该函数的返回,该函数不返回任何内容(因此未定义)。即使你要退回$ .get电话,你也不会得到你想要的东西。您需要登录回调函数或使用promise。
function getUsername() {
return $.get("http://www.roblox.com/mobileapi/userinfo", function(data) {
console.log(data.UserName);
return data.UserName;
});
}
getUsername().done(function(username) { console.log(username); });
#2
0
Function getUsername
executes a $.get
request, but it returns nothing and it ends here.
函数getUsername执行$ .getrequest,但它不返回任何内容,它在此处结束。
You have to log your data in the function of your asynchronous $.get
request. This function (function(data)) is a callback function. It will be called, if the response of your $.get
request arrive.
您必须在异步$ .get请求的函数中记录您的数据。该函数(函数(数据))是一个回调函数。如果您的$ .get请求的响应到达,它将被调用。