javascript - 如何从异步函数获取返回值到 React Native 中的变量?
问题描述
我有一个带有身份验证过程的 React Native 应用程序。为了获得身份验证,我使用异步存储来存储令牌并检索令牌。
我创建了一种从异步存储中获取令牌的方法,但问题是,我不能通过将令牌分配给另一个变量来在其他函数中使用它。我创建的方法的函数调用总是返回一个 Promise 而不是令牌。
应用程序.js
const getToken = async () => {
var value = "";
try {
await AsyncStorage.getItem('accessToken').then(val => {
value = val;
})
} catch (e) {
console.log("error getting token", e)
}
console.log("token", value) // here I can see the correct token
return value;
}
const AuthRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => {
if (Auth.isAuthenticated()) {
var idToken = getToken().then(t => { return t });
console.log("token", idToken) // here it is a Promise
if (idToken) {
return <Component {...props} />
}
return <Redirect to={{ pathname: `/signup` }} />
}
else {
// return <Component {...props} />
return <Redirect to={{ pathname: `/signup` }} />
}
}} />
)
我该如何解决这个问题?
解决方案
一旦你有了 Promise,所有依赖于 Promise 的代码都需要使用 Promise.then(functionThatDoesMoreThings) 链接起来,或者你需要等待 Promise... 然后执行操作。
大多数人更喜欢异步/等待......所以在你的情况下,它看起来像:
const AuthRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={async props => {
if (Auth.isAuthenticated()) {
var idToken = await getToken();
console.log("token", idToken) // it should print the token
if (idToken) {
return <Component {...props} />
}
return <Redirect to={{ pathname: `/signup` }} />
}
else {
// return <Component {...props} />
return <Redirect to={{ pathname: `/signup` }} />
}
}} />
推荐阅读
- java - 为什么我的 Java 程序中的好友列表不显示?
- python - 在 python 程序中查看浮点数的真实值
- firebase - 如何使用 App Inventor 从存储在 Firebase 中的数据中删除“/”/“”
- javascript - 单击按钮时如何为背景生成随机颜色?
- cassandra - Cassandra 过滤两列
- bazel - 如何避免在 Bazel 中构建后删除缓存文件
- mysql - MySQL Workbench“旧”语法改变了吗?
- http-status-code-404 - 404 在 ngrok 上找不到
- javascript - iOS - JSValue 保留但不释放对象
- logical-operators - 给定 A∧B 仅使用 → 和 ⊕(Xor) 的等价物是什么