JavaScript 返回一个承诺,即使它向控制台打印一个字符串

JavaScript returning a promise even though it prints a string to the console

我正在尝试创建一个函数,该函数 return 是一个包含 jwt 令牌的字符串,Amplify return 中使用的函数是一个承诺,我无法理解承诺,但在之后有些挣扎,我已经设法让我的函数从承诺中获取我需要的字符串并将其打印到控制台但是当我然后从函数中 return 这个字符串所以我可以从不同的地方调用它结果数据现在又是一个承诺。不知道我做错了什么。

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.

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

如果你在一个函数中使用了 await ,它只会 return 一个 Promise 无论如何你可以只使用

getToken().then(console.log)

// or

getToken().then(token => console.log(token))

// both are same

因为你不能在异步函数之外使用 await 作为反应应用程序的问题,只需使用状态,例如在承诺的 .then 中使用 setState() 更新应用程序状态 return编辑。不需要使函数异步。

或者如果您真的希望组件是异步的,而不是仅仅研究 <Suspense> 以响应处理必须在显示之前从网络获取数据的组件

像这样使用它。

let result = null
getToken().then(token => {
    result = token

    // Now you can use the result variable
    console.log(result)
})

感谢@tfarmer4 和@Arish Khan,我想我现在已经怀疑了。在我的脑海里,我想把令牌作为一个字符串变量,这样我就可以将它传递给我的 API 调用函数,但我现在意识到我需要从每个函数中调用它,所以下面是我的示例解决方案。

function getToken() {
  return Auth.currentAuthenticatedUser().then(result => result.signInUserSession).then(result => result.accessToken).then(result => result.jwtToken);
}

function callAPI () {
  getToken().then(data => {
    let token = data;
    console.log(token);
    //more lines here such as calling my API using token as the variable of the jwt token
    }
  );
};