0

I'm very new at Javascript. I had some issue going on with my script I had to loop through $.get and I stuck in a loop here is my code

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]

    for (var i = 0; i < a.length; i+=1){
       .$get('url' + "?params=" + a[i],function(data2){             
           school = data2['data']; 
        });
    }

    console.log(school);

When I tried to console.log(school) it keeps showing "object{}"

How can I get the data outside loop?

I would be really grateful if you can help me with this issue.

Thanks.

1
  • 2
    Welcome to the wonderful world of async! You can't do that. Commented Oct 1, 2014 at 19:40

2 Answers 2

1

you must use the callback function or something like this.

because the $.get is async function and when

console.log(school);

execute(!) the school is not evaluated yet.

you can use some things like this.

    a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]

    for (var i = 0; i < a.length; i+=1){
       .$get('url' + "?params=" + a[i],function(data2){             
           school = data2['data']; 
           console.log(school);
        });
    }

or

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]
var  school ={};
for (var i = 0; i < a.length; i+=1){
   .$get('url' + "?params=" + a[i],function(data2){             
       school = data2['data']; 
       whenitready();
    });
}

function whenitready(){
   console.log(school);
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you need to wait until all your requests are done, you need something like this:

var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
  endpoints.push($.get('url' + '?params=' + a[i]));
}
$.when.apply($, endpoints).done(function () {
  // Function arguments array differs if we have one or more than one endpoint.
  // When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
  // When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
  // Normalize the single endpoint to the generic list one.
  var args = endpoints.length > 1 ? arguments : [arguments];
  for (var i = 0; i < args.length; i++) {
    var data = args[i][0];
    // Do stuff here with every data received...
    school = ... 
  }

  console.log(school);
});

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.