How to use Promises with button in Javascript?

Asked

Viewed 104 times

3

Hello, I’m a beginner in Javascript and I wanted to create a code where we write something in the input and when clicking a button we would call a Promise. It would try to make a request on the site and return the result or an error message.
I’m making requests in the git api as a test where a user’s name is passed in input.
The problem is I don’t know what the final part would look like. If I leave ' = gitPromise() ' it would already be calling the function and since inputElement is not defined yet, it gives error. If I try to change only to ' = gitPromise ', it is not possible to use . then and . catch.
Grateful from now on.
Follows the code:

var inputElement = document.querySelector('input');
var buttonElement = document.querySelector('button');

var gitPromise = function() {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.github.com/users/' +
    inputElement.value);
    xhr.send(null);

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText));
        } else {
          reject('Erro na requisição');
        }
      }
    }
  });
}

buttonElement.onclick = gitPromise().then(function(response) {
  console.log(response);
})
.catch(function(error) {
  console.log(error);
});
<html>
    <head>
        <meta charset="utf-8">
        <title>Program Teste</title>
    </head>
    <body>
        <div id="teste">
            <input type="text" placeholder="Digite um texto aqui">
            <button>Adicionar</button>

        </div>
        <script src="program.js"></script>
    </body>
</html>

  • Your difficulty is how to use that Promisse you encoded?

  • I’m sorry, maybe it wasn’t very clear. I rephrased the question for better understanding.

  • @Betatester, in this case, I advise you to use the Fetch API, which is a Promisse-based request API. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

1 answer

3


Hello @Beta Tester,

Its implementation is wrong on the following point:

buttonElement.onclick = gitPromise().then(function(response) {
  console.log(response);
})
.catch(function(error) {
  console.log(error);
});

Your code should be like this:

buttonElement.onclick = function(){
    gitPromise().then(function(response) {
      console.log(response);
   })
   .catch(function(error) {
      console.log(error);
   });
};

This way your password will only be executed when the user clicks the button in question, the way you had written the password will be executed as soon as the code is read by the interpreter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.