Redux 等待异步 thunk 继续进行

Redux await async thunk keeps going

我目前正在使用 redux / redux-thunk 像这样使用 api-sauce 获取用户

let authToken = await AsyncStorage.getItem('@TSQ:auth_token')

if (authToken) {
  store.dispatch(fetchUser(authToken))
  console.log('show login screen')
  // dont worry, if the token is invalid, just send us to onboarding (api determines this)
  loggedInView()
} else {
  Onboarding ()
}

....

export const fetchUser = authToken => async dispatch => {
  console.log('dispatching auth token')

  console.log('here goes request')
  let res = await api.get(`/auth/${authToken}`);

  if (res.ok) {
    console.log('have the user')
    dispatch(
      setUser(res.data)
    )
  } else {
    dispatch({
      type: 'SET_USER_DEFAULT'
    })
}

}

当此代码为运行时,用户仍在加载并且console.logs顺序不对

`dispatching auth token`
`here goes request`
`show login screen`

为什么会这样?

这是因为对 store.dispatch(fetchUser(authToken)) 的实际调用是同步的 - dispatch() 方法 is not asynchronous,因此记录 "show login screen" 将在 [= 执行后立即发生14=]方法。

如果你希望loggedInView()在你的网络请求返回响应后执行(即调用异步方法api.get()),那么你可以考虑重构你的代码如下方式:

if (authToken) {
  store.dispatch(fetchUser(authToken))
  // Remove navigation from here
} else {
  Onboarding ()
}

然后:

export const fetchUser = authToken => async dispatch => {
  console.log('dispatching auth token')

  console.log('here goes request')
  let res = await api.get(`/auth/${authToken}`);

  if (res.ok) {
    console.log('have the user')

    // Occurs after network request is complete    
    console.log('show login screen')

    // Add navigation here to go to logged in view now that request is complete
    loggedInView()

    dispatch(
      setUser(res.data)
    )
  } else {
    dispatch({
      type: 'SET_USER_DEFAULT'
    })
}

希望对您有所帮助!