Using Promise Javascript

Asked

Viewed 78 times

2

Hello, I have a requisition GET in Jquery, to load a page HTML; and if the page does not exist, then displays in the container a <div>erro 404</div.

The Jquery request works well.

Jquery request

const loadHtml = (url, element) => {
    $.get(url, function(response) {
        $(element).html(response);
    }).fail(function() {
        $(element).html('<div>erro 404</div>');
    })
}

However I want to remove Jquery from the application and in this case I want to use javascript puro, so I thought I’d use Promise.

It turns out that when the página HTML Does not exist, the message displayed in the container is not <div>erro 404</div>, and yes to server message 404.

Can help me better the code below so that if the page does not exist I can display the <div>erro 404</div> ?

Promise

const loadHtml = (url, element) => {
    fetch(url, {
        method: 'get' // opcional
    })
    .then(function(response) {
        response.text()
        .then(function(result) {
            console.log(result);
            $(element).html(result);
        })
    })
    .catch(function(err) {
        $(element).html('<div>erro 404</div>');
    });
}

2 answers

3

You did wrong, first you need to check if the request was ok and after such verification use the promisse again to redeem the values, example:

const elemento = document.getElementById("elemento");
const divError = '<div>erro 404</div>';
const loadHtml = (url, element) => {
    fetch(url, {
        method: 'get' // opcional
    })
    .then(function(response) {
        if (response.ok){ // verifica se houve sucesso
            response.json() // aplicando a chamada novamente e resgatando o resultado
              .then(function(result) {            
                elemento.innerHTML = JSON.stringify(result);
              });
        } else { // a requisição aconteceu algum problema
            elemento.innerHTML = divError
        }        
    })
    .catch(function(err) {
        elemento.innerHTML = divError
    });
}
loadHtml('https://viacep.com.br/ws/01001000/json/', elemento);
<div id="elemento">Carregado ...</div>

I’d do it a little differently:

const elemento = document.getElementById("elemento");
const divError = '<div>erro 404</div>';
const loadHtml = async (url, element) => {
  try {
    const p = await fetch(url, { method: 'get' });
    const r = await p.json();
    elemento.innerHTML = JSON.stringify(r);
  } catch {
     elemento.innerHTML = '<div>erro 404</div>';
  }
}
loadHtml('https://viacep.com.br/ws/01001000/json/', elemento);
<div id="elemento">Carregando ...</div>

Links

  • But in this case the return is being a json, in the example I passed I am requesting an HTML page. Example: loadHtml('pages/page.html', elemento) ?

  • @Wagnerfillio the same way ... the result is different but the way to get to it is the same

3


The question isn’t even the Promise, the question is you understand the fetch API, understood the basics then will be able to use, since Promise is something more general and "changes the behavior" (in the received parameters) according to the location that is applied, so to make clear, HTTP request has nothing to do with Promise, in the case of fetch it receives the interface Response for an HTTP response and this is what you will get the 404 specific error (remember there are several possible types of errors), in case you can use the property Response.status

Example:

fetch(url, {
    method: 'get'
}).then(function(response) {
    if (response.status == 404) {
        ... faz algo ...
    } else if(response.ok) {//Verifica se esta dentro do 2xx. que são de sucesso
        ... faz algo ...
    } else {
        ... outros erros HTTP, faz algo ...
    }
})

If you want to deal with catch there just issuing a reject, because HTTP status is not exceptions or errors or a throw new Exception, are responses and the catch captures 'errors' or 'rejections', but for the case Promise.reject resolve, could just do this:

fetch(url, {
    method: 'get'
}).then(function(response) {
    if (response.ok) {//Verifica se esta dentro do 2xx. que são de sucesso
        ... faz algo ...
    } else {
        return Promise.reject(response); //Envia o response para o catch
    }
}).catch(function (response) {
    if (response.status == 404) {
        ... faz algo ...
    } else {
        ... outros erros HTTP, faz algo ...
    }
});
  • Thank you for the reply, so to summarize, Promise is a return of the fetch method, which returns a sponse, and from there on I can do the checks and if I want to return a json, I’ll use the method json(), similarly, if I want to return a string, I can use the method text();

  • @Wagnerfillio more or less, Promise is something that can be used in almost everything from Javascript, basically it’s a stand-alone feature, it can be used even alone, it’s something you can build, but yes, fetch uses itinternally to facilitate and with it you can work the catch in case of waiting obligatorily a json, if it is not json you can do similar to what I did on return Promise.reject(response);, getting something like:

  • fetch(url, { method: 'get' }).then(function(response) { if (response.ok) { return response.json(); } else { return Promise.reject(response); } }).then(function (responseJson) { /*algo aqui*/ }).catch(function (response) { if (response.status == 404) { ... faz algo ... } else { ... outros erros HTTP, faz algo ... } }); ... in the /*algo aqui*/ you will manipulate the json you received, because so facilitates dividing into different thens

Browser other questions tagged

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