0

I've got this code:

function fetchSocialCount(type,fileSrc){
    var count = {likes: 0, dislikes: 0};
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            var countResponse = json_encode(req.responseText);
            count.likes = countResponse.likes;
            count.dislikes = countResponse.dislikes;
            return count;
        }
    }
}

So, I want to return count from the req.onload function expression, as if it was returned from the fetchSocialCount function. How can I achieve this?

bool3max
  • 2,748
  • 5
  • 28
  • 57
  • 1
    *"How can I achieve this?"* You can't. Just like you have to assign a function to `onload` to get the response, the caller of `fetchSocialCount` has to pass a function to `fetchSocialCount` (or something similar). This is one of the most asked JavaScript questions on Stack Overflow. – Felix Kling Oct 07 '15 at 15:43

1 Answers1

2

req.onload is asynchronous. You need to use callbacks, promises, or something similar to get the resulting "count"

function fetchSocialCount(type,fileSrc, cb){
    var count = {likes: 0, dislikes: 0};
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            var countResponse = json_encode(req.responseText);
            count.likes = countResponse.likes;
            count.dislikes = countResponse.dislikes;
            cb(count);
        }
    }
}

//calling fetchSocialCount
fetchSocialCount(my_type, my_file_src, function(count){
    //here it is
    console.log(count);
});
Alex Yurkowski
  • 1,676
  • 1
  • 12
  • 26