javascript - How to get function return result? -


i developing file reading service this:

angular.factory('fileservice', fileservice);  function fileservice($cordovafile){     var service = {         readfile: readfile     };      return service;      ///////////////      function readfile(path, file){         $cordovafile.readastext(path, file)         .then(function (success) {             console.log("read file success");             console.log(success);             return success;         }, function (error) {             alert("fail read file:"+error);             console.log("fail read file");             console.log(error);             return false;         });     } } 

and using this:

var data = fileservice.readfile(cordova.file.datadirectory,filename); console.log(data) //return undefined 

the problem fail return data. how can data return back?

your problem not returning result readfile function. returning data callback functions if come think of it...that result returned function readfile , stays inside function. want return whole result of function readfile , resolve promise in controller use it. here code:

angular.factory('fileservice', fileservice);  function fileservice($cordovafile){         var service = {         readfile: readfile     };      return service;      function readfile(path, file){         return $cordovafile.readastext(path, file);     } } 

and use this:

var data = fileservice.readfile(cordova.file.datadirectory,filename); data.then(function (success) {         // whatever need result     }, function (error) {        /// handle errors     }); 

in general, when use services implement kind of functionality uses promises , returns result, should return promise object can resolved anywhere needed. highly recommend read great explanation promise objects.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -