Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - How can I access a variable outside a promise `.then` method?

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"

This is my method:

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)
    })
  }
};

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.

I need to $scope that variable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
        })
    }
}

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
   });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...