javascriptreactjsreact-native

Using async and await with export const


I can't make this work...it's says: await is a reserved word. Yes, of course it is...and I'd like to use it :)

What's wrong ?

export const loginWithToken = async () => {
  return dispatch => {
    dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true})
    let storedData = await ReadFromLocalDB('user')
    console.log(storedData)
    if (!storedData) {
        invalidToken(null, dispatch)
    }
    else {
        storedData = JSON.parse(storedData)
        SessionLoginWithToken(storedData.session.token).then(res => {
            console.log(res)
            loginSuccessfully(res, dispatch, true)
        })
    }
  }
}

My ReadFromLocalDB function looks like this:

export const ReadFromLocalDB = async (key) => {
   return AsyncStorage.getItem(key)
}

It returns a promise


Solution

  • return dispatch => {...} needs to also be async I believe. Right now, only the top level function is async, not the nested one.

    // This function is async
    export const loginWithToken = async () => {
      // This one is not though which means it can't use await inside
      // return dispatch => {
    
      // Instead it should likely be:
      return async dispatch => {
        dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true})
        let storedData = await ReadFromLocalDB('user')
        console.log(storedData)
        if (!storedData) {
            invalidToken(null, dispatch)
        }
        else {
            storedData = JSON.parse(storedData)
            SessionLoginWithToken(storedData.session.token).then(res => {
                console.log(res)
                loginSuccessfully(res, dispatch, true)
            })
        }
      }
    }