I can’t get a variable out of a function

Asked

Viewed 13 times

0

I’m trying to make a currency converter, but I can’t get the object out of the fetch, although I read this question don’t understand yet what I should do, I am obliged to make the conversion within the then? even using an asynchronous function, how do I use "dataFinal" out of the?

const pegaDados = () => {
  let url = `https://economia.awesomeapi.com.br/json/all/${moedaFinal.value}-BRL`;
  let dadosFinais;

  if (moedaInicial.value != "R$") {
    url = url + `,${moedaInicial.value}-BRL`;
  }

  fetch(url)
    .then((response) => response.json())
    .then((dados) => {
      dadosFinais = Object.assign(dados);
    });

  console.log(dadosFinais);

};
  • Yes, you will always have to deal with the data within the then. Or use asynchronous function. But even using the asynchronous function (which by itself also returns, "implicitly", a promise when it is called), the then and catch still should, in theory, be used to have knowledge of when the "asynchronous processing" was finalized. See Using promises on MDN.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.