javascript - Console will not wait for file load before printing -


i have file containing json data want read. found code reading file @ neontribe.co.uk, can't seem console wait load complete.

function ondeviceready(){ window.resolvelocalfilesystemurl(cordova.file.externaldatadirectory, function(fs) { var directoryreader = fs.createreader(); directoryreader.readentries(function(entries) { var i; (i=0; i<entries.length; i++) {  document.addeventlistener('deviceready', ondeviceready2, false);   function ondeviceready2() {       function readfromfile(filename) {         var pathtofile = cordova.file.externaldatadirectory + filename;         window.resolvelocalfilesystemurl(pathtofile, function (fileentry) {             fileentry.file(function (file) {                 var reader = new filereader();                  reader.onloadend = function (e) {                 console.log("inside load" + json.parse(this.result));                     return json.parse(this.result);                 };                  reader.readastext(file);             }, errorhandler.bind(null, filename));         }, errorhandler.bind(null, filename));     }       function some_function(callback) {      console.log("inside function1");      var data = readfromfile(entries[i].name);      callback(data); }    some_function(function(data) {       console.log("data!" + data);     console.log("data string!" +  json.stringify(data));  });     //  var obj = json.parse(data);   // console.log("arresteefirst!" + data.arresteefirst);    // console.log("data!" + data); } console.log(entries[i].name); }   }, function (error) { alert(error.code); }); }, function (error) { alert(error.code); }); } 

when run output in console:

inside function1 data!undefined data string!undefined 1452034357845.json inside load[object object]

so looks goes some_function , prints inside function 1. not wait function pass result load. prints 2 lines callback function straight away. prints filename (at end of loop) , prints console message within load function. looks returning object according console data should not undefined.

there few bits wrong code, because it's not written taking account asynchronous calls , assuming happens in synchronous fashion.

the callback(data) within some_function(callback) in fact called after called var data = readfromfile(entries[i].name);. 2 issues arise here.

  1. function readfromfile(filename) doesn't return data (actually, doesn't return @ all);
  2. reader.readastext(file); treated asynchronous. in nutshell, means code keep running (in case print messages) , call reader.onloadend callback once data loaded - late message has been printed.

there several ways fix code, way use promises. bluebird promises personally. promises, solution (pseudo-code):

function readfromfile(filename) {    return new promise(resolve, reject) {        var pathtofile = cordova.file.externaldatadirectory + filename;        window.resolvelocalfilesystemurl(pathtofile, function (fileentry) {            fileentry.file(function (file) {                var reader = new filereader();                  reader.onloadend = function (e) {                     console.log("share results... " + json.parse(this.result));                     resolve(json.parse(this.result));                 };                  reader.readastext(file);             }, errorhandler.bind(null, filename));         }, errorhandler.bind(null, filename));     } // return promise }  function some_function(callback) {     console.log("inside function1");      var promise = readfromfile(entries[i].name);      promise.then(callback); // called when promise resolved }  some_function(console.log); 

promises allows conceptually return "contract" value fetched , functions waiting value (.then) called once data received , promise resolved (you can reject promise if fails well). (sorry bad explanation, there loads of better documentation on internet, recommend taking @ it).

i hope helps, there other ways of coming around problem, believe promises might elegant without getting generators.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -