![](/img/trans.png)
[英]How can I access the promise result from outside of the promise body
[英]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.log中記錄了名稱,並在控制台中獲得了正確的值。 但是僅在我調用函數getUser()
可以使用,即使返回names變量也undefined
得到undefined
。
我需要$scope
該變量。
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;
})
}
}
上面的答案回答了為什么在調用getUser()
時得到undefined
原因,但是如果要使用最終結果,您還想更改使用從getUser獲得的值的方式-它返回一個promise對象,而不是end您所追求的結果,因此您的代碼要在承諾得到解決時調用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.