【问题标题】:How can I access a variable outside a promise `.then` method?如何访问 promise `.then` 方法之外的变量?
【发布时间】:2018-05-13 13:52:51
【问题描述】:

我正在开发一个 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)
    })
  }
};

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

我需要$scope 那个变量。

【问题讨论】:

  • 我猜你有 return names,但你还需要 return Spotify.getCurrentUser()... 以便它返回承诺(以及最终的返回值)

标签: javascript angularjs angular-promise


【解决方案1】:

getUser() 没有返回任何内容。你需要从Spotify.getCurrentUser()返回promise,然后当你在那个中返回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 的 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
   });

【讨论】:

  • 对不起,我是新来的,它有效,但我得到一个以 $$state 开头的对象我如何访问它包含的数据?
  • 你能帮帮我吗?
  • 我添加了一些代码来处理您从 getUsers() 获得的承诺 - 我认为这比我之前在评论中链接的其他答案要干净得多。
  • 所以then里面的函数会返回一个值,然后getUser会返回?
  • @Melab yes - getUser() 返回一个承诺。您可以在该承诺的 then 函数中访问其最终解析值
【解决方案2】:

如果你这样使用它,你可以使用 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();

【讨论】:

  • 我们可以在函数减速中不添加异步的情况下使用等待吗?
  • 不,你不能在没有异步的情况下使用await,如果你尝试使用你会得到同样的错误。
猜你喜欢
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2018-06-12
  • 2019-10-14
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多