json - How do I use the data returned by an ajax call? -


i trying return array of data inside json object return url, can see data being returned using console.log.

however when trying catch return array in variable example:

var arr = list(); console.log(arr.length); 

the length being output code "0" despite fact data returned has content (so length greater zero). how can use data?


list: function() {          var grades = [];             $.getjson(          "https://api.mongolab.com/api/1/databases", function(data) {              console.log(data);              grades [0] = data[0].name;              console.log(grades.length);           });           return grades; }, 

the issue facing easy snagged on if aren't used concept of asynchronous calls! never fear, you'll there.

what's happening when call ajax, code continues process though request has not completed. because ajax requests take long time (usually few seconds) , if browser had sit , wait, user staring in angsuish @ frozen screen.

so how use result of ajax call?

take closer @ getjson documentation , see few hints. asynchronous functions getjson can handled in 2 ways: promises or callbacks. serve similar purpose because 2 different ways let specify once ajax finished.

callbacks let pass in function getjson. function called once ajax finished. you're using callback in example code wrote, it's callback being defined inside of list() method isn't useful.

promises let pass in function promise returned getjson, called once ajax finished.

since doing inside of method, have decide 1 you're going support. can either have method take in callbacks (and pass them along) or can have method return promise returned getjson. suggest both!

check out:

var list = function(success) {   // pass in callback passed function.  getjson call when data arrives.   var promise = $.getjson("https://api.mongolab.com/api/1/databases", success)    // returning promise getjson provides, allow caller specify promise handlers   return promise; }  // using callbacks list(function(grades) {   console.log(grades); });  // using promises list()   .success(function(grades) {     console.log(grades);   }); 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -