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

313
Visualizações
Returning value from a promise (asyncronously validating a form)

It's my first post here and please pardon me for my english. Here's the problem i've encountered: I am trying to validate user's address when submitting a form using an external API. My goal is to prevent form from submitting based of an asynchronously defined variable (which is the error). I would like to somehow return a variable from an async function (variable is redefined after a promise-based request to the API). Here is the code:

function validateAdress(requestString) {
  callToTheAPIMethod(request).then((res) => {
    let error;
    const obj = res.getDataFromApi ...obj data from async call
    const precision = ...parameters from an API on which i rely in order to set up the error message

    if (obj) {
      switch (precision) {
        case "exact":
          error = "";
          break;
        case "number":
        case "near":
        case "range":
          error = "Adress is incorrect. Please specify house number";
          break;
        case "street":
          error = "Adress is incorrect. Please specify house number";
          break;
        case "other":
        default:
          error = "dress is incorrect. Please specify smth...";
      }
    } 
    $(".address_error").text(error);
     return error;
  });
} 


function validateForm() {
validateAdress(requestString)

if (validateAdress(requestString) return false 
///i get it that i am not able to return the variable directly from this call, only a promise to resolve
/// if error is not empty prevent form from submitting

...some other code validating input fields
}

As a result the error variable gets assigned with a text string specifying type of an error and it is added to the DOM. validateAdress function is called in some other function which is used to validate a form on a client-side. The problem is that i am trying to prevent the form from submitting if the variable error has been assigned with a value. It seems to me that it is not possible to do so. If i am trying to return that variable from validateAdress functions it is obviously returning undefined... Unfortunately, i am also not able to use async/await syntax here.. I would highly appreciate if someone can give me a hint how to implement that sort of functionaly or how to access the error variable.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can call preventDefault on the form submit handler, call the async function, if everything is OK, call the forms submit method.

eg..

const form = document.querySelector('form');
const input = document.querySelector('input');

function check(done) {
  setTimeout(() => {
    done(input.value === '1');
  }, 1000);
}

form.addEventListener('submit', e => {
  e.preventDefault();
  check(ok => {
    if (ok) form.submit();
    else console.log('try again.');
  });
});
Type 1 into input and press enter, and wait 1 second..

<form>
  <input />
</form>

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