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

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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