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

90
Visualizações
Use fetched API data outside of the function

To make my code cleaner I want to use fetched API data in a few different functions, instead of one big. Even though I 've did manage to reffer to that data in other functions, the problem is the API im a fetching throws different, randomized results every time it is called. And so the output from userData() does not equal that from userData2(), even though my intention is different and I'd like the result variable contents to be the same between functions.

const getData = () =>
  fetch("https://opentdb.com/api.php?amount=10").then((response) =>
    response.json()
  );

const useData = async () => {
  const result = await getData();
  console.log(result);
};

const useData2 = async () => {
  const result = await getData();
  console.log(result);
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your getData() function returns a promise. One fun fact about promises is that while they can only resolve once, that resolved value can be accessed and used as many times as you want.

const dataPromise = getData();

const useData = async () => {
  const result = await dataPromise;
  console.log(result);
};

const useData2 = async () => {
  const result = await dataPromise;
  console.log(result);
};

Using await resolves the promise value, the equivalent of...

dataPromise.then((result) => {
  console.log(result);
});
// or `dataPromise.then(console.log)` if you like brevity

I like to point this out about the fetch-api... you should always check the Response.ok property

const getData = async () => {
  const res = await fetch("https://opentdb.com/api.php?amount=10");
  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }
  return res.json();
};
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