Handling synchronous and asynchronous request results

Asked

Viewed 353 times

2

I have a function that triggers an ajax request for a route, see:

var getInstituicoesSemUsuario = function(tipo)
{
    var resultado = "";

    $.ajax(
    {                       
        url: "{{path_for('instituicao.sem.responsavel')}}",
        data: "tu=" + tipo,
        type: "GET",
        async: false,                       
        success: function(resposta)
        {
            resultado = resposta;
        }
    });

    return resultado;
}

With the option async defined for false it is possible to get the return of the function getInstituicoesSemUsuario(), however, Google Chrome issues the following warning:

Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience.

In a nutshell, a synchronous call seems to affect the end-user experience.

However, if I remove the option async or define it to true the warning goes away, but, I can’t get the result of the request.

Doubts

  1. How can I get the result of an asynchronous ajax request?
  2. Why a synchronous request affects the user’s experience?
  3. There are scenarios where I can use synchronous requests?

1 answer

1


Answers:

  1. How can I get the result of an asynchronous ajax request?

You have to use callbacks, Promises or async/await. You can read more here on asynchronous function chaining alternatives.

  1. Why a synchronous request affects the user’s experience?

Imagine that the server you are contacting is slow to respond, or not at all... then the browser is blocked waiting forever and you have to reload the page or close the browser in order to use it again. In the case of a shopping cart for example this can be very bad for the user who loses what was saved.

  1. There are scenarios where I can use synchronous requests?

No. Nowadays this is obsolete == prohibited.


On the specific problem in the question, it is similar to this other, and you can solve as the alternatives I indicated in 1.. An example with deferred (jQuery) could be like this:

var getInstituicoesSemUsuario = function(tipo) {
  return $.ajax({
    url: "{{path_for('instituicao.sem.responsavel')}}",
    data: "tu=" + tipo,
    type: "GET"
  });
}

// e depois quando precisares:
getInstituicoesSemUsuario('foo').done(function(resultado) {
  console.log(resultado);
});
  • 1

    @Thank you Andersoncarloswoss! I was inglezar too :) Out of curiosity I went looking for and found this.

Browser other questions tagged

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