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);
};
동기화 방법으로 비동기를 수행하는 것이 불가능합니다. –
죄송합니다 - 질문을 잘못 읽었습니다! 내 대답은 업데이 트되었습니다 :) –
내가 대답하기 전에 뭔가를 확인하자 ... 그래서'stackNavigator.router.getStateForAction = (action, state)'는 async'를 사용할 수 없습니까? 예 :'stackNavigator.router.getStateForAction = async (action, state)'? – ReyHaynes