Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
How to implement Javascript async/await/promise in both of AsyncStorage and Json.parse?

Everyone, Here is my dirty code.

const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])

Expected console state order is

1, 2, 3

Real console state order is

3, 1, 2

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms. so I need to wait all of them. This is basic of javascript concept: async, sync, promise. Please help me, seniors!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You are not awaiting the call to getAuthStateData in your useEffect callback, so it runs asynchronously, and the rest of the callback keeps running synchronously until the runtime has time to run the other tasks you've given it.

I think you meant to write this instead:

useEffect(async () => {
  const authStateData = await getAuthStateData();
  console.log('3', authStateData);
}, []);
about 4 years ago · Juan Pablo Isaza Denunciar

0

The main issue is the missing await before getAuthStateData(), but you're missing some dependencies and cleanup as well. See inline comments:

const parseJson = (value) => { //not async -- see next comment
  try{
    const parsedData = JSON.parse(value); //JSON.parse is not an async method, so there's no reason to await here
    console.log('2', parsedData);
    return parsedData;
  }catch(e){
    console.error(e);
  }
}

const _getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){
    console.error(e);
  }
}

//get a memoized version of the callback
const getAuthStateData = React.useCallback(_getAuthStateData,[])

useEffect(() => {
  async function asyncFunc() {
    const authStateData = await getAuthStateData();
    console.log('3', authStateData);
  }
  asyncFunc(); //prevent a linter error about using an `async` function directly inside `useEffect` by wrapping an async function and calling it
},[getAuthStateData]) //because we use getAuthStateData, it should be a dependency -- that's why we memoized it above
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda