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



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

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.

如果您在函数中使用了 await,那么无论如何它只会返回一个 Promise,所以你可以使用

getToken().then(console.log)
// or
getToken().then(token => console.log(token))
// both are same

由于您不能在异步函数之外使用 await 作为 react 应用程序的问题,只需在返回的承诺.then中使用setState()更新应用程序的状态等状态。 不需要使函数异步。

或者,如果您真的希望组件是异步的,而不仅仅是在 React 中学习<Suspense>来处理必须在显示之前从网络获取数据的组件

像这样使用它。

let result = null
getToken().then(token => {
result = token
// Now you can use the result variable
console.log(result)
})

我想我现在多亏了@tfarmer4和@Arish汗。在我的脑海中,我想将令牌作为字符串变量获取,以便我可以将其传递到我的 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
}
);
};

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

相关内容

最新更新