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

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