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

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

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

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