我正在编写一个 React Native 应用程序。有没有办法在返回值之前解决非异步函数中的 Promise?
样本:
const f = () => {
return new Promise((resolve) => {
resolve('baz')
})
}
const foo = () => {
const a = f() // a is now a Promise
return a
};
console.log(foo) // `foo` is a Promise, I need 'baz'
我想找到一种方法来获取已解析的值f
,但我无法进行foo()
异步。有没有办法做到这一点?如果没有,任何想法如何解决这个问题?
这是我经过一些清理的真实代码:
const stackNavigator = new StackNavigator(...)
const defaultGetStateForAction = stackNavigator.router.getStateForAction
stackNavigator.router.getStateForAction = (action, state) => {
let screenToRequest = undefined
let defaultState = undefined
const isInitial = action.type === 'Navigation/INIT'
if (isInitial) {
defaultState = MainTabs.router.getStateForAction('Navigation/INIT')
screenToRequest = defaultState.routes[defaultState.index].routeName
} else if (action.type === 'Navigation/NAVIGATE') {
screenToRequest = action.routeName
}
if (screenToRequest) {
const screen = screens.getScreen(screenToRequest)
/**
* If screen requires login, check if user is logged in
*/
if (screen.screen.loginRequired) {
/**
* Here I would like to read data from AsyncStorage with
* `await` but that's not possible due to this function
* not being `async` and it cannot be since router does not
* seem to support it.
*
* getSession() reads data from AsyncStorage. If I could
* `await getSession()`, I would not have a problem.
*/
const session = getSession()
// Use `session` to determine if user is logged and act accordingly
}
}
return defaultGetStateForAction(action, state);
};