How do I return a variable from a callback function in javascript? -


i need return value of tempvar can't figure out how since result of callback. correct way handle this? i'm not sure how word problem. hoping work doing var tempreturned = readpwfile('filename.txt'); doesn't obvious reasons if have 'return' somewhere in callback. main goal return results of txt file variable. can point me in right direction?

function readpwfile(filename) {     var tempvar;     window.requestfilesystem(localfilesystem.persistent, 0, function (filesystem) {         filesystem.root.getfile(filename, null, gotreadfileentry, fail);     });      function gotreadfileentry(fileentry) {         fileentry.file(gotfile, fail);     }      function gotfile(file) {         readdataurl(file);     }      function readastext(file) {         var reader = new filereader();         reader.onloadend = function (evt) {             tempvar = evt.target.result;         };         reader.readastext(file);     } } 

you should provide callback through api grant access variable passing callback argument.

another alternative use through use of promises, allow work on object may not have result yet.

for instance function declaration should

function readpwfile(filename, callback) { 

and invoked with

readpwfile(filename, function(tempvar) {      alert("successfully received tempvar"); }); 

in essence code bind callback function reader, rather using code. unless want mutate result in someway of course :

function readpwfile(filename, callback) {     ...      function readastext(file) {         var reader = new filereader();         // preference user's passed in callback function on previous implementation         reader.onloadend = callback;         reader.readastext(file);     } } 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -