jQuery.Deferred exception (AJAX, JSON Array Object) -


my first function gets json array object via jquery ajax request. second function tries access object, hit "jquery.deferred exception: unable property '1' of undefined or null reference..." (note '1' refers trying access ojson[1].name shown in following code.)

here json:

[{"name":"alpha", "numwalks":1},{"name":"beta","numwalks":2}] 

here code: (note: have save json .txt file , parse json because of how sharepoint site set up.)

var ojson; $("document").ready(function() {   gettext().done(getdogs()); });  function gettext() {   var deferred = $.deferred();   $.get("dogwalksjson.txt", function(returnedtext) {     ojson = json.parse(returnedtext);   });   deferred.resolve();   return deferred.promise(); }  function getdogs() {   console.log(ojson[1].name); } 

if console.log(ojson[1].name) in gettext() function, works. when try access info getdogs() function, exception. guess it's trying access info before it's ready (if try access browser's console, works), why added defer/promise.

anyone have suggestions how can fix this?

thanks!

my guess it's trying access info before it's ready

indeed. you're calling deferred.resolve early, , you're calling getdogs() instead of passing then.

avoid deferred antipattern , global ojson variable, use

$("document").ready(function() {   gettext().then(getdogs  ); //                      ^^ no call });  function gettext() {   return $.get("dogwalksjson.txt")   .then(function(returnedtext) { // chain promise     return json.parse(returnedtext); // fulfill parsed object   }); }  function getdogs(ojson) {   console.log(ojson[1].name); } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -