简体   繁体   中英

variable in function not updating global

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;
}

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
});

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM