javascript 如何在 promise `.then` 方法之外访问变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47559836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access a variable outside a promise `.then` method?
提问by Rodolfo R
I'm working on a Spotify app. I'm able to login and get my token. My problem is I cannot access a variable outside the method. In this case "getCurrentUser"
我正在开发 Spotify 应用程序。我可以登录并获取我的令牌。我的问题是我无法访问方法之外的变量。在这种情况下"getCurrentUser"
This is my method:
这是我的方法:
function getUser() {
if ($localStorage.token == undefined) {
throw alert("Not logged in");
} else {
Spotify.getCurrentUser().then(function(data) {
var names = JSON.stringify(data.data.display_name);
console.log(names)
})
}
};
As you can see I console.logged the name and I do get the right value in the console. But only works there if I call the function getUser()I get undefinedeven with a return of the names variable.
正如您所看到的,我在控制台中记录了名称,并且确实在控制台中获得了正确的值。但只有在我调用函数时getUser()才能在那里工作,undefined即使返回名称变量也是如此。
I need to $scopethat variable.
我需要$scope那个变量。
采纳答案by Danny
getUser()is not returning anything. You need to return the promise from the Spotify.getCurrentUser(), and then when you return nameswithin thatit is returned by the outer function.
getUser()没有返回任何东西。你需要从返回的承诺Spotify.getCurrentUser(),然后当你回到names内即它是由外部函数返回。
function getUser() {
if ( $localStorage.token == undefined) {
throw alert("Not logged in");
}
else {
return Spotify.getCurrentUser().then(function(data) {
var names = JSON.stringify(data.data.display_name);
console.log(names)
return names;
})
}
}
The above answered why you were getting undefinedwhen calling getUser(), but if you want to work with the end result you also want to change how you're using the value you get from getUser - it returns a promise object, not the end result you're after, so your code wants to call the promise's thenmethod when the promise gets resolved:
以上回答了您undefined在调用时得到的原因getUser(),但是如果您想使用最终结果,您还想更改使用从 getUser 获得的值的方式 - 它返回一个 promise 对象,而不是您的最终结果之后,所以你的代码想要then在承诺得到解决时调用承诺的方法:
getUser() // this returns a promise...
.then(function(names) { // `names` is the value resolved by the promise...
$scope.names = names; // and you can now add it to your $scope
});
回答by Jorge Monroy
If you use it like that you can use the awaitcall
如果你像那样使用它,你可以使用await调用
function getUser() {
if ( $localStorage.token == undefined) {
throw alert("Not logged in");
}
else {
return Spotify.getCurrentUser().then(function(data) {
var names = JSON.stringify(data.data.display_name);
console.log(names)
return names;
});
}
}
const names = await getUser();

