我正在开发 Spotify 应用程序。我能够登录并获取我的 token 。我的问题是我无法访问方法外的变量。在这种情况下 "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)
})
}
};
如您所见,我在 console.logged 中记录了名称,并且在控制台中得到了正确的值。但只有当我调用函数 getUser()
时,我才会在那里工作,即使返回了 names 变量,我也会得到 undefined
。
我需要$scope
那个变量。
最佳答案
getUser()
未返回任何内容。您需要从 Spotify.getCurrentUser()
返回 promise ,然后当您在 that 中返回 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;
})
}
}
上面回答了为什么你在调用 getUser()
时得到 undefined
,但是如果你想使用最终结果,你也想改变你的方式使用您从 getUser 获得的值 - 它返回一个 promise 对象,而不是您所追求的最终结果,因此您的代码希望在 promise 得到解决时调用 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
});
关于javascript - 如何访问 promise `.then` 方法之外的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47559836/