Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda