Skip to content Skip to sidebar Skip to footer

JQuery $.get() Within For Loop Scope

I'm new to working with AJAX, but I've been researching it for the past two hours to help in my scenario. I haven't made any progress. :( Regardless, my issue is that the subPages

Solution 1:

Your for loop immediately executes all iterations of the loop. The subPages array is populated after the last line of console.log has run.


Solution 2:

$.get is asynchronous, so after calling it, the code inside .then is not immediately called. So, it continues to the next iteration of your loop, finally exits, and shows an empty subpages array, because your data hasn't returned yet.

Here's a quick idea of how to wait for your ajax calls, prior to logging the array (untested):

var ajaxCalls = [];
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
    // grab all <a> within response text
    var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
        var $response = $(responseData);
        var $links = $response.find('a');
        // push each valid link into subPages array
        $links.each(function(index, $link){
            if(this.href.indexOf(containsSub) > -1){
                subPages.push(this.href);
            }
        });
        // subPages array is loaded with the correct values
        console.log("subPages inside get: " + subPages);
    });
    ajaxCalls.push(getLinks);
}

$.when.apply(null, ajaxCalls).then(function() {
    // not empty here
    console.log("subPages outstide all: " + subPages);
});

Solution 3:

issue is that the subPages array is out of scope when I'm outside $.get(...)

$.get() returns an asynchronous response . Try chaining .then() to $.get() to maintain same scope as initial .then()

var getLinks = $.get(baseURL + pages[i]).then(function(responseData){

})
.then(function() {
  console.log("subPages outstide all: " + subPages);
})

Try creating an IIFE within for loop to pass i

e.g.,

var pages = ["a", "b", "c"];

for(var i = pages.length -1; i >= 0; i--) {
  (function(j) {
  var dfd = $.Deferred(function(d) {
    setTimeout(function() {
      d.resolve(j)
    }, Math.random() * 1000)
  }).promise()
  .then(function(n) {
    console.log("first", n, pages[n]);
    return n
  }).then(function(res) {
    console.log("second", res, pages[res])
  })
  }(i))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Post a Comment for "JQuery $.get() Within For Loop Scope"