Get value read from file by a function back in caller : Windows Store JavaScript App -


i have written following code [windows store javascript app] :

function get_ver(){      get_text("verfile");      // how value read get_text [i.e. variable filedata] in function???  }   function get_text(filepath) { var p = "ms-appx:///" + filepath; var uri = new windows.foundation.uri(p); windows.storage.storagefile.getfilefromapplicationuriasync(uri)    .then(function (samplefile) {        return windows.storage.fileio.readtextasync(samplefile);    }).done(function (filedata) {           document.getelementbyid("t").innerhtml = filedata;         // want return filedata get_ver()    }    );  } 

i want access data read 'verfile' [i.e. value of variable filedata] inside get_ver() may return value. how so?

instead of setting value innerhtml of element want should returned caller can processed further.

because get_text method calling async api work, becomes async api. return value it, then, need return promise value. easiest way return promise last then in chain, , in return final value innermost completed handler.

that is, write method this:

function get_text(filepath) {     var p = "ms-appx:///" + filepath;     var uri = new windows.foundation.uri(p);     return windows.storage.storagefile.getfilefromapplicationuriasync(uri)         .then(function (samplefile) {             return windows.storage.fileio.readtextasync(samplefile);         }).then(function (filedata) {             document.getelementbyid("t").innerhtml = filedata;             return filedata;         });  } 

notice changed "done" "then" promise chain. inserted return filedata in innermost completed handler, , return statement before first async call. return promise whole chain, , fulfillment value of promise (according definition of then) return value of last completed handler. (if want more explanation this, second edition preview of book, http://aka.ms/brockschmidtbook2) has whole appendix called "demystifying promises."

because get_ver receives promise back, add completed handler promise (using done because you're @ end of chain):

function get_ver(){      get_text("verfile").done(function (filedata) {          // use filedata      }); } 

does make sense? general pattern returning values functions use async apis, makes functions async.

.kraig


Comments