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

165
Vistas
How to store data from async function into global variable?

I'm trying to build a page that displays a random quote with a <button> that changes the quote for each click.

This is the async function:

let quote, author;


async function getData() {
    const response = await fetch('https://type.fit/api/quotes');
    const data = await response.json();
    const random = await data[Math.floor(Math.random() * data.length)];
    quote = random.text;
    author = random.author;
}

getData() works I can log author and quote into it, but I can't use the returned value outside of the function. I know that async function always returns a Promise so I have to use .then but I have to write new functions that use the data retrieved by getData() as:

function foo(quote, author){
....do stuff
} 

The new function must modify the HTML code to change author and quote. The only solution that came to my mind is to create a function that contains everything (a huge chain of .then) and then pass it to the <button> via onclick. But it seems like a stupid and chaotic thing, and it wouldn't be a Promise anyway since it's the result of .then?

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

0

You can create author and quote variable in the function to re-decalre them every time when function is called

cosnt {quote, author} = data[randomNumber]

in here you grab quote and author keys in the called data

every onClick these variable will be re-decalread and you will be able insert them as DOM Element innerHTML

You can check my solution How I would do that

const quoteText = document.querySelector("h1")
const authorText = document.querySelector("p")
const btn = document.querySelector("button")

async function grabNewQuote(){
  const response = await fetch("https://type.fit/api/quotes")
  const quotes = await response.json()
  
  let randomNumber = Math.floor(Math.random() * quotes.length)
  //Math.floor() -> rounds the number to down if random number is
  //3.99 it will output 3
  //Math.random() randomly picks up number between length size and 0
  
  const {text, author} = quotes[randomNumber]
  quoteText.innerHTML = text
  authorText.innerHTML = author
}

btn.addEventListener("click", grabNewQuote)
<h1><h1>
<p></p>
<button>New Quote 🎉</button>

Also you could use .then but it would make big mess in the code and it would be less readable

if you are comfortable with .then() you can replace that following code up there

await fetch("https://type.fit/api/quotes")
.then(response => response.json())
.then(quotes = > {
  let randomNumber = Math.floor(Math.random() * quotes.length)

  const {text, author} = quotes[randomNumber]
  quoteText.innerHTML = text
  authorText.innerHTML = author
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try something like this:

const quote, author;
const myQuote = document.querySelector("#myQuote")
const myButton = document.querySelector("#myButton")

async function getData() {
    const response = await fetch('https://type.fit/api/quotes');
    const data = await response.json();
    const random = await data[Math.floor(Math.random() * data.length)];
    quote = random.text;
    author = random.author;
    myQuote.textContent = quote + "By: " + author

}

getData()

myButton.addEventListener("click", getData);

The takeaway is that you have to update your HTML within the async function, if you do it outside it might not be available yet because it's async, not sync. One way to do it, at least.

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