如何访问promise` .then`方法之外的变量?

Rod*_*o R 5 javascript angularjs angular-promise

我正在开发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)
    })
  }
};
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我在控制台上记录了名称,并且我在控制台中获得了正确的值.但是只有在我调用函数时getUser()才能在那里工作,undefined即使返回了names变量.

我需要$scope那个变量.

Dan*_*nny 5

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;
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

上面回答了你undefined在调用时得到的原因getUser(),但如果你想使用最终结果,你也想改变你从getUser获得的值的方式 - 它返回一个promise对象,而不是最终的结果你是之后,所以你的代码想要then在promise得到解决时调用promise的方法:

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
   });
Run Code Online (Sandbox Code Playgroud)