Because readFile
is asynchronous, everything that uses this must also be asynchronous.
Here is an approach:
var fetchMySuperFile = new Promise(function(resolve, reject) {
fs.readFile('myfile','utf8', function (err, data){
resolve(JSON.parse(data));
});
};
fetchMySuperFile.then(function(mySuperFile) {
// OK, you have it now.
});
This can still be useful. The nature of javascript promises is you can invoke fetchMySuperFile.then
multiple times, but it will still have only called readFile
one time.
Of course, since it's angular, you might want to use $q
instead of Promise
. The reason why is that, after a $q
has resolved, angular refreshes. (You won't need to invoke $scope.$apply()
)