Javascript Promise With Runtime Error

Asked

Viewed 189 times

0

I’m trying to solve the following exercise:
Create a screen with one that should be named after a user on Github. After typing the user name and click search button. The application should search for the Github API (as per URL below) the user repositories data and show them on screen: Example URL: https://api.github.com/users/diego3g/repos Just change "diego3g" by user name. After filling in the input and adding, the information must fill in a list.

I can not understand why to run before I click the send and still go straight to the . catch.

I appreciate all your help!

var lista = " "; 
var linha = " ";
var perfil = " ";
var textoLinha = " ";

var minhaPromise = function(){    
    return new Promise(function(resolve, reject){
        var x = document.getElementById("user").value;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", 'https://api.github.com/users/'+x+'/repos');
        xhr.send('null');

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4) {
                if (xhr.status === 200){                       
                    resolve();                    
               } else {
                   reject();
                  
                }
            }
        }
    });
}

minhaPromise() 
    .then(function() {
            lista = document.querySelector('#corpo ul');  
            perfil = JSON.parse(xhr.responseText) || [];for(var dados of perfil){
                linha = document.createElement('li');
                textoLinha =  document.createTextNode(Object.values(dados));
                linha.appendChild(textoLinha);
                lista.appendChild(linha);  
           } 
           })   
        
    .catch(function(){
        lista = document.querySelector('#corpo ul');                 linha = document.createElement('li');
        textoLinha = document.createTextNode("Não encontrado.");
        linha.appendChild(textoLinha);
        lista.appendChild(linha); 
    });  
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="desafio2.js"></script>
    </head>
    <body>
        <div id="corpo">
            <input type="text" name="nome" id="user" />
            <input type="submit" value="Enviar"  onclick="minhaPromise()" />
            <ul></ul>
        </div>
    </body>
</html>

1 answer

3


I can’t understand why I run before I click

It’s simple... take a good look at the code you wrote:

  • created a function called minhaPromise
  • but then you’re calling this function with minhaPromise()

but there’s more :)

  • if for some reason the xhr.readyState is not 4 had never solved anything
  • your promise must pass on the data received resolve(xhr.responseText)
  • its rejection should pass a new Object Error: reject(new Error('texto a passar'))
  • and a mistake is to call an asyncronous function in onclick="minhaPromise()"

to solve your problem, you just have to change the code a little bit:

  • resolve and reject correctly
xhr.onreadystatechange = function() {
    return xhr.readyState === 4 && xhr.status === 200
        ? resolve(xhr.responseText)
        : reject(new Error('Something off!'))
}
  • involve the call minhaPromise() in an office, so that it can be executed, only when we want
var onButtonClick = function() {
    minhaPromise()
        .then(function(data) { 
            // "data" é o objecto com o texto do request
            // perfil = JSON.parse(data) || [];
        })
        .catch(function(err) {
            // "err.message" contem "Something off!"
        })
}
  • in the boot, call this new function (and do not use Submitpois nao tem qualquerform`, a normal boot is sufficient)
<button onclick="onButtonClick()">Enviar</button>

I’ve stopped using the XMLHttpRequest for some time, since then I use the fetch and if you want to see your project work, with the changes I’ve specified, you can see in Codepen

Browser other questions tagged

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