首页 > 解决方案 > 即使将字符串打印到控制台,JavaScript也会返回一个promise

问题描述

我正在尝试创建一个返回包含 jwt 令牌的字符串的函数,Amplify 中使用的函数返回一个承诺,我无法理解承诺,但经过一番努力,我设法让我的函数得到我从承诺中需要的字符串并将其打印到控制台,但是当我从函数中返回这个字符串以便我可以从不同的地方调用它时,结果数据现在再次成为一个承诺。不知道我做错了什么。

async function getToken() {
  let userData = await Auth.currentAuthenticatedUser().then(result => result.signInUserSession).then(result => result.accessToken).then(result => result.jwtToken);
  console.log(userData); // this prints the token perfectly as text to the console
  return(userData); // I want this to return the token as a string not a promise
}

console.log(getToken(); // this prints a promise to the console again even though I've got it to a string in the function.

标签: javascriptaws-amplify

解决方案


编辑:这里的沙盒你所需要的就是我相信的这个编辑。请记住,异步函数只是 Promise。您必须通过将结果设置为带有 的变量来对结果进行任何工作let data = await Auth.currentAuthenticatedUser().then(result => result).then(data => data.jwtToken),或者只需在.then(data => {data.jwtToken //...your work here}).


推荐阅读