Dealing with synchronous and asynchronous request results

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 set to false you can get the return of the getInstituicoesSemUsuario() function, 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 set it to true the warning disappears, but I can not get the result of the request.

Questions

  • How can I get the result of an asynchronous ajax request?
  • Why does a synchronous request affect the user experience?
  • Are there scenarios in which I can use synchronous requests?
  • asked by anonymous 12.08.2017 / 17:35

    1 answer

    1

    Answers:

  • How can I get the result of an asynchronous ajax request?
  • You need to use callbacks , promises or #. You can read more here about chaining alternatives for asynchronous functions .

  • Why does a synchronous request affect the user experience?
  • Imagine that the server you are contacting is slow to respond, or it does not respond at all ... then the browser is frozen waiting forever and you have to reload the page or close the browser before you can use it again. In the case of a shopping cart for example this can be very bad for the user who loses what was recorded.

  • Are there scenarios in which I can use synchronous requests?
  • No. Nowadays this is obsolete == forbidden.

    About the actual problem in the question, it's similar to this one , and you can work out how the alternatives I indicated in 1. . An example with deferred (the jQuery promise) might look 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);
    });
    
        
    12.08.2017 / 17:40