Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!