Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7004271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T21:10:38+00:00 2026-05-27T21:10:38+00:00

I’m having some difficulty with an array that is (outside of an asynchronous call)

  • 0

I’m having some difficulty with an array that is (outside of an asynchronous call) perfectly well-defined but when I call its indices inside an asynch request (e.g. $.getJSON) all the indices of the array are undefined but the length is still the same. Here is my code.

The array I am referring to is friendsArray

The array has the correct index during the second “$.getJSON” call but inside the callback of that function all its indices become undefined. Shouldn’t the array keep its values since it was defined within the scope of the method?

if (response.status === 'connected') { 
var accessToken = $.trim(response.authResponse.accessToken);
var hashArray = [];
var friendArray = [];
document.getElementById("statusCheck").innerHTML = accessToken;
$.getJSON('https://graph.facebook.com/me/friends?access_token=' + accessToken, 
  function(dataJSON){
    hashArray = dataJSON['data'];
    for (var i = 0; i < hashArray.length; i++){
        friendArray.push(hashArray[i]["id"]);
    }
    var resultJSON = "{";
    var resultArray = [];

    for (var i = 0; i < friendArray.length; i++){
        $.getJSON('https://graph.facebook.com/me/mutualfriends/' + 
                  friendArray[i] + "?access_token=" + accessToken, 
            function(dataJSON2){
                resultArray = dataJSON2['data'];
                resultJSON += friendArray[i] + ":" + resultArray.length + ",";
                //alert(resultJSON);
            })
        if (i == friendArray.length - 1){
            postArrayPopulation(resultJSON);
        }
    }

});         

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T21:10:39+00:00Added an answer on May 27, 2026 at 9:10 pm

    The problem is that the callback function happens some time later when the ajax function completes. By then, the array index has advanced to the end of your for loop (thus it points off the end of the array) to an undefined value. The array is still there, but your index has been changed by the time the completion function is called.

    The technique usually used to get the index into the success handler is to capture it in a function closure where it gets captured for use in the completion function.

    You can create a closure that captures the index value by replacing your success handler with this:

    (function(index) {
        return function(dataJSON2) {
            resultArray = dataJSON2['data'];
            resultJSON += friendArray[index] + ":" + resultArray.length + ",";
            //alert(resultJSON);
        }
    }) (i);
    

    This outer function executes and creates a closure which captures the value of i and uniquely makes it available to the success handler. When it self executes, it returns your success handler which is thus passed to the getJSON function to be called later. But, when it is called later the value of i that you need is available to the success handler via the argument in the self executing function.

    Here’s another way to think about closures used with callbacks.

    1. Any function has access to all the variables that are within scope when it’s declared, even variables that are up at a higher level in parent scopes and even if the function is called later as a callback. This is actually a huge feature of javascript that many other languages do not have.
    2. So, if we want a variable to be available to a callback function later when the callback executes, we just need to somehow get that variable into the scope of that callback function.

    Here’s an example of that:

    function cycleOnOff(sel, cnt, delay) {
        var obj = $(sel);
    
        function next() {
            if (cnt-- > 0) {
                obj.toggle();
                setTimeout(next, delay);
            }
        }
        next();
    }
    

    In this case, the function next() is a callback to setTimeout(), but that function has full access to the variables within its parent scope: sel, cnt, delay and obj.

    1. If the variable doesn’t change between the time the callback is initially set and when the callback gets called, then it’s pretty easy. You can just use an anonymous function declaration and all higher scope variables available at the time of defining the anonymous function will still be available when the callback is called at some later time.
    2. If the variable does change as code continues to execute and you want to make a specific value that it has now available to the callback when it is later called – this is when it gets a little trickier. What one can do is to create a function that you pass this variable into, thus creating a scope where that variable has the value you want and where it won’t change as the other code continues to execute. But, because what we want is a callback function, not just a function call, we have to combine the two in a semi-weird way. We make a function call and pass it the desired value. In that function call, we return a reference to our callback function. This assigns the callback function appropriately, but it puts the callback function into a closure that captures the value of our desired variable. Even better, this closure is unique to this particular instance of the callback so every use of the callback will have it’s own closure and thus it’s own unique value of that variable. The closure/callback we created for your particular problem is an example of this.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.