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?
– novic
I’m sorry, maybe it wasn’t very clear. I rephrased the question for better understanding.
– Beta Tester
@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
– MarioAleo