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

84
Vistas
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 Respuestas
Responde la pregunta

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 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