-1

i have following function in the AbgularJS service:

var readFile = function (path, file) {
            console.info("Trying to read file with URI: " +path+ " "+file);
            $cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);
                var deferred = $q.defer();
                $cordovaFile.readAsText(path, file)
                    .then(function (success) {
                        // success
                        console.log("Success");
                        console.log(success);
                        deferred.resolve(success);
                    }, function (error) {
                        console.error(error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            }, function (error) {
                console.log(error);
            });
        }

in the success callback is defined function for file reading.

But i always get exception message on this place:

TypeError: Cannot read property 'then' of undefined

But if i do following:

$cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);

            }, function (error) {
                console.log(error);
            });

it works fine.

I would like to execute file reading only if file is exist, but i don;t know hot to do it in the right way.

Service method is called by this way:

DeviceSrv.readFile(cordova.file.externalRootDirectory+"/"+APP_CONST.MP3_FOLDER_NAME+"/sounds/", APP_CONST.MP3_FILE_NAME)
                .then(function(value){
                    console.log(value);
                    var parsedObject = JSON.parse(value);
                    console.log(parsedObject);
                    $scope.availableSounds = parsedObject.availableSounds;
                    $scope.availablePrepreparedSounds = parsedObject.availablePrepreparedSounds;
                });

How i should update my code to execute code in the right way?

Many thanks for any advice.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
redrom
  • 11,502
  • 31
  • 157
  • 264
  • Avoid the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572)! Although if it says that `readAsText` doesn't return a thenable, you might have to use a deferred together with old-school callbacks. – Bergi Jul 27 '15 at 17:19

1 Answers1

0

Since promises can be chained, you can just return the entire promise, without the need for creating deferred.

   var readFile = function (path, file) {
    console.info("Trying to read file with URI: " +path+ " "+file);
    return $cordovaFile.checkFile(path, file).then(function (success) {
        return $cordovaFile.readAsText(path, file);
     }).then(function (success) {
           // success
           console.log("Success");
           console.log(success);
      }).catch(function (error) {
           console.error(error);               
      });
  }
Scorpion-Prince
  • 3,574
  • 3
  • 18
  • 24