如何在 promise `.then` 方法之外访问变量?
How can I access a variable outside a promise `.then` method?
我正在开发 Spotify 应用程序。我能够登录并获取我的令牌。我的问题是我无法访问方法外的变量。在这种情况下 "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()
时才在那里工作,即使名称变量的 return 我得到 undefined
。
我需要$scope
那个变量。
getUser()
没有 returning 任何东西。您需要 return 来自 Spotify.getCurrentUser()
的承诺,然后当您 return names
在 中 它是 return由外部函数编辑。
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 - 它 return 是一个 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
});
如果你这样使用它,你可以使用 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();
我正在开发 Spotify 应用程序。我能够登录并获取我的令牌。我的问题是我无法访问方法外的变量。在这种情况下 "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()
时才在那里工作,即使名称变量的 return 我得到 undefined
。
我需要$scope
那个变量。
getUser()
没有 returning 任何东西。您需要 return 来自 Spotify.getCurrentUser()
的承诺,然后当您 return names
在 中 它是 return由外部函数编辑。
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 - 它 return 是一个 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
});
如果你这样使用它,你可以使用 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();