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

185
Visualizações
How to use information obtained asynchronously?

Every time this site loads, it gets some info in a database, sums everything and appends it in a '#total' div. I'm trying to update the value every time a new input is submitted. I thought that since the submission would occur after the site were loaded, if I tried to get the '#total' value on submit, it would be already defined but if I try to console.log it, it says it's undefined.

How could I use '#total' value after the sum were appended to it?

const route = 'http://localhost:3000';
const tot = document.getElementById('total');

serverInteraction(route).then((data) => {
    data.forEach((T, i) => {
        arr[i]= parseFloat(arr[i]);
        console.log(T.Value);
    });

    var total =  arr.reduce((sum, n) => sum + n);
    return total;
    
}).then(total => appendTotal(total));

function handleSubmit(event) {
    event.preventDefault();
    const currentTime = new Date();
    const newContent = {valor: valor.value, produto: produto.value, date: currentTime.toDateString(), time: `${currentTime.getHours()}:${currentTime.getMinutes()}`};
    serverInteraction(route, 'POST', newContent);
    const total = document.getElementById('total');
    const inputValue = parseFloat(valor.value);
    total.innerText = (total.value + inputValue);
    console.log(total.value);
}

async function serverInteraction(route, method = 'GET', content = null) {
    if (content) content = JSON.stringify(content);
    const response = await fetch(route, {
        method: method,
        body: content,
        headers: {"Content-type": "application/json"}
    })
    return response.json();
}

function appendTotal(aTotal) {
    tot.append(aTotal);
}
about 4 years ago · Juan Pablo Isaza
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