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

205
Visualizações
Async function makes it hard to access variable because variable is not "ready" when it is needed

I have problems with my variable keys. getAllKeys saves keys into the variable keys. I want to use keys in prepareDate but when the code gets to prepareDate it does not work because the values are not yet asignt to variable keys (because of this JavaScript Async stuff)

I need to know how I can wait until keys is "ready" so prepareDate (and the rest of the code) can work with keys. There is .then and promise (if this is the right solution) but I do not know how to use them here.

  let keys = [];

  const getAllKeys = async () => {
    try {
      keys = await AsyncStorage.getAllKeys();
    } catch (e) {
      // read key error
    }
    console.log("keys: ", keys) // This works, the keys are saved inside keys
  }

  const getData = async (key) => {
    try {
      const jsonValue = await AsyncStorage.getItem(key);
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
      // error reading value
    }
  };

  const prepareData = () => {
    console.log("keys: ", keys)
    keys.forEach((key) => {   // I want that this works but there is nothing inside keys.. 
      console.log("hier")
      console.log(getData(key))
    })
  }

  getAllKeys();
  prepareData();
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Stop using a global variable keys. Instead, return a value from getAllKeys (so that getAllKeys() returns a promise for that), and accept the keys as a parameter to preprateData:

const getAllKeys = async () => {
  try {
    return await AsyncStorage.getAllKeys();
  } catch (e) {
    // read key error
    return [];
  }
};

const prepareData = async (keys) => {
  const data = Promise.all(keys.map(key => {
    console.log(key);
    return getData(key);
  }))
  console.log(data);
  return data;
}

Now you can use them as

getAllKeys().then(prepareData);

or in

(asnyc () => {
  const keys = await getAllKeys();
  console.log("keys: ", keys) // This works
  await prepareData(keys);
})();
about 4 years ago · Juan Pablo Isaza Relatório

0

You could postpone the call to prepareData until after getAllKeys is finished, like so:

getAllKeys().then(prepareData);

We can do that because getAllKeys is an async function and thus returns a Promise, which allows us to call the then-method on it.

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