0

I am trying update the global variable from the response I get. I know my scopes are messed up somehow and I tried finding an example but couldn't find one that matched this. I'm new at javascript so any syntax tips would help as well. Any help would be great!

    hit_count: function(permalink) {

    var count = 0,
    perm = permalink,
    url;

    if(perm) {
        url = 'http://www.mysite.com?q=scope:' + perm + '&callback=?';

        $.getJSON(url, function(result){
           count = result.count;
           //want this to update global count or at least return this count
           if(count > 1) {
               count = count - 1;
           }

        });
    }

    return count;
}
2
  • 5
    $.getJSON is asynchronous so this won't work. When you do return count, $.getJSON might not be done yet. Can you show us how you use the function. Commented Jan 9, 2014 at 23:08
  • @putvande i literally just call it from another function as count = parseInt(trend_count(params.permalink), 5); Commented Jan 9, 2014 at 23:13

2 Answers 2

1

The problem is that $.getJSON is asynchronous. In this code,

$.getJSON(url, function(result){
  //...
  count = count - 1;
});
return count;

The statement return count; is executed before the JSON request is complete. That means that the line count = count - 1 will execute long after count has been returned.

The typical way to deal with this is to pass a callback function to execute when the request is done. In your example, you could do this.

hit_count: function(permalink, callback) {
  //...
  $.getJSON(url, function(result){
    //...
    count = count - 1;
    callback(count);
  });
}

Which you can then call like this:

hit_count(permalink, function(count) {
  // code to execute once the request is complete
});
Sign up to request clarification or add additional context in comments.

Comments

0

Trouble is, you cannot get the updated value of count before the Ajax request is complete and the handler hidden behind getJSON actually calls your handler.

It would be like assuming the recipient of a letter read it as soon as you dropped it into the mailbox.

You might want to count two different things:

1) the number of letters sent
2) the number of acknowledgements from the guys who read them.

Since the letters will need time to travel (the request transiting back and forth from the browser to the server) and a letter could even be lost (an Ajax request could fail), you cannot assume both counts will always be equal.

Here your handler code tries to count the letters safely arrived home, while hit_count handles the same counter as the number of letters sent.

This can only end in tears :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.