$. GET Jquery Dùvida

Asked

Viewed 70 times

4

I have the 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;
};

Because the $.get Asynchronous is always returning the empty list? How to solve this?

2 answers

2


You have to change the logic of the arguments of that method. Since it is asynchronous you have to use callbacks (or Promise) to run code when it has an answer to give you. What happens is that Javascript frees the process $.get and before waiting for the answer continues to run the next line which is the return returnList;. That line is therefore race before of the $.get have 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 be 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
});
  • I made the change in my getContributors method. but the error persists. I will edit it for you to see how I am trying to access the method.

  • @Josevieiraneto do not change the question. Create a jsFiddle to see the code

  • guy already edited.. I will but create jsFiddle

  • @Josevieiraneto the problem is that all the code has to be inside that callback, the console.log and the for next.

  • @Have you seen my comment? The code should look like this: https://jsfiddle.net/xb9z1xcg/

  • 1

    Thanks, it worked out :)

Show 1 more comment

0

I strongly recommend that you do not work synchronously with AJAX. Synchronous requests are obsolete and this makes a lot of sense, in one language Single-Thread, competing with renderings of HTML and CSS in the browser, the use of synchronous requests tend to be a bad practice (I don’t see a case that’s 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 just use the method correctly in the place where it is 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 a little deeper: Promises (what 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 idea of task js. Several libraries have mechanisms to work with this idea, the Q.js has a function (Q.Spawn) to the same idea of task js.

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

Browser other questions tagged

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