如何在 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()
返回承诺,然后当您在 that 内返回 names
时,它由外部函数返回.
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 获得的值 - 它返回一个承诺对象,而不是您所追求的最终结果,因此您的代码希望在承诺得到解决时调用承诺的 then
方法:
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屋!