$ .GET JQuery Doubt

4

I have method:

RepoApi.prototype.getContributors = function() {
    var returnList = [];
    $.get(this.url).done(function(response) {
        console.log(response);
        returnList = response;
    }).fail(function(response){
        console.log(response);
    });

    return returnList;
};

Why does $.get asynchronous always return the empty list? How do I resolve this?

    
asked by anonymous 05.05.2016 / 17:14

2 answers

2

You have to change the logic of the arguments for this method. Since it is asynchronous you need to use callbacks ( or Promise) to run code when he has an answer to give you. What happens is that JavaScript frees the $.get process and before waiting for the response it continues to run the next line which is return returnList; . This line is therefore before of $.get has been received, hence your variable is never set.

I suggest something like this:

RepoApi.prototype.getContributors = function(callback) {
    $.get(this.url).done(function(response) {
        callback(null, response);
    }).fail(function(response){
        callback(true, response);
    });
};

And then when you use it would look something like this:

RepoApi.getContributors(function(err, res){
    if (err) return console.log('Houve um erro!');
    // a partir daqui podes usar a array "res" dentro desta função 
    // ou funções chamadas por esta
});
    
05.05.2016 / 17:48
0

I strongly recommend that you do not work synchronously with AJAX. Synchronous requests are obsolete, and this makes a lot of sense in a Single-Thread language, competing with HTML and CSS rendering in the browser, use of synchronous requests tend to be a bad practice (I do not see a case that is seen as a good idea, maybe someone knows, but to this day I've NEVER seen).

You can tailor your code to work asynchronously easily:

RepoApi.prototype.getContributors = function() {
  return $.ajax({
    method: 'GET',
    url: this.url
  });
};

Now you just need to use the method correctly where it's called, for example:

var repo = new RepoApi();
repo.getContributors()
  .done(function(response) {
    console.log(response);
  }).fail(function(response){
    console.log(response);
  });

Working with AJAX asynchronously is the ideal way, but if you are dissatisfied with the way you have to work with asynchronous (using Promises ), you have two other options:

  • Study further: Promises (or which jQuery implements in this case with the #done #fail methods, although it does not follow the ECMA-defined interface) and Generators , then take a look at the task.js idea. Many libraries have mechanisms to work with this idea, the Q.js has a function ( Q.spawn ) for the same idea as task.js .

  • Study async-await , an ES7 feature that solves all these problems in a simple and elegant way. There are some preprocessors that allow the use of async-await , which can even be solved with the idea of task.js .

05.05.2016 / 18:08