如何访问promise` .then`方法之外的变量? [英] How can I access a variable outside a promise `.then` method?
问题描述
我正在开发Spotify应用。我能够登录并获取我的令牌。我的问题是我无法访问方法之外的变量。在这种情况下getCurrentUser
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"
这是我的方法:
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)
})
}
};
正如您所见,我在控制台上记录了该名称,并且我在控制台中获得了正确的值。但是只有在我调用函数 getUser()
时才能在那里工作,即使返回names变量,我也得到 undefined
。
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 undefined
even with a return of the names variable.
我需要 $ scope
该变量。
推荐答案
getUser()
没有返回任何内容。您需要从 Spotify.getCurrentUser()
返回承诺,然后在中返回名称
它由外部函数返回。
getUser()
is not returning anything. You need to return the promise from the Spotify.getCurrentUser()
, and then when you return names
within that it is returned by the outer function.
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;
})
}
}
上面回答了为什么你在调用 getUser()
时得到 undefined
的原因,但是如果你想使用最终结果你也想改变你从getUser获得的值的方式 - 它返回一个promise对象,而不是你所追求的最终结果,所以你的代码想要调用promise的<承诺得到解决时code>然后方法:
The above answered why you were getting undefined
when 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 then
method when the promise gets resolved:
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
});
这篇关于如何访问promise` .then`方法之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!