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

141
Vistas
EventListener function not calling second function asynchronously

I have a series of functions that all link together as part of a calculator application.

There is a submit-type button with a click eventListener() and an anon function that executes two functions.

The first function in the eventListener() is an API-call function that pulls in data and changes the form input values depending on the appropriately clicked button. The intended goal here is that the next function in the eventListener() which is the umbrella calculation function then calculates using the new input values as called in by the API function and displays this in a summary box.

Now, the code does work but only when I click the button twice. The first click will call the API and then I have to click the button again to change the values in the summary box. I'm not sure why they are not executing async.

It is worth mentioning that the calculation summary box functions can also be triggered by a keyup function in the input values i.e. user manually entering details. This works no issue but I really need these button clicks to behave the same way.

// THIS IS THE SUMMARY BOX FUNCTION WHICH HOUSES ALL THE CALCULATION FUNCTIONS. A,B,C ETC. REPRESENTS A <P> HTML ELEMENT IN THE SUMMARY BOX.

const valuesToChange = () => {
      a.innerText = `£${calculationFunctionA()}`;
      b.innerText = `${calculationFunctionB()} BTC`;
      c.innerText = `£${calculationFunctionC()}`;
      d.innerText = `£${calculationFunctionD()}`;
      e.innerText = `£${calculationFunctionE()}`;
    };
    
// THESE ARE THE FORM INPUT VALUES. WHEN USER MANUALLY ENTERS INPUT, THE CALCULATION FUNCTION IS TRIGGERED VIA KEYUP EVENTLISTENER.

    const innerElementsArr = [formInput, formInput1, formInput2];
    innerElementsArr.forEach(item => {
      item.addEventListener('keyup', function() {
        valuesToChange();
      });
    });
    
// API CALL FUNCTION THAT REPLACES THE FORM INPUT VALUES WITH THE JSON DATA.

    const getValues = APIIndex =>
      fetch('https://api.com')
        .then(response => response.json())
        .then(
          json =>
            (formInput.value = `${parseFloat(json.prop[APIIndex].price).toFixed(
              2
            )}`)
        )
        .catch(error => console.log('Error'));
    
// SUBMIT BUTTON THAT CALLS BOTH FUNCTIONS ABOVE.

    mySubmit.addEventListener('click', () => {
      getValues(0);
      valuesToChange();
    });
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The click event triggers both functions synchronously and doesn't wait for the api call to respond. you should call the second function from within then like this.

    const getValues = APIIndex =>
      fetch('https://api.com')
        .then(response => response.json())
        .then(
          json =>
            (formInput.value = `${parseFloat(json.prop[APIIndex].price).toFixed(
              2
            )}`)
            valuesToChange(); //call the second function
        )
        .catch(error => console.log('Error'));
    
// SUBMIT BUTTON THAT CALLS BOTH FUNCTIONS ABOVE.

    mySubmit.addEventListener('click', () => {
      getValues(0); //call the first function
    });
about 4 years ago · Juan Pablo Isaza Denunciar
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