Cordova FileSystem Async


#1

Hello,
i have a problem with the Cordova FileSystem plugin ( https://github.com/apache/cordova-plugin-file/blob/dev/doc/index.md ).

The problem is, the plugin works asynchronous. Let me show my code.

In my “service.js” i have a factory with returns like:

    checkFile: function (fileTyp) {
        
        window.requestFileSystem(window.PERSISTENT, 1024*1024, function(filesystem) {
            filesystem.root.getFile('/bpa_json/'+ fileTyp +'.json', {create: false}, 
                function() {
                    return true;
                },
                function() {
                    return false;
                }
            );
        });

    },
    
    createFile: function (fileTyp) {
        
        window.requestFileSystem(window.PERSISTENT, 1024*1024, function(filesystem) {
            if(filesystem){
                        
                filesystem.root.getFile('/bpa_json/'+ fileTyp +'.json', {create: true},
                    function(fCreateSuccess) {
                        alert("FILE CREATED");
                    }
                );
            
            }
        });
    
    }

I use the factory in my controller like:

    if(FileService.checkFile('topnews')) {
        alert("FILE EXIST");
    } else {
        FileService.createFile('topnews');
    }

So, the problem is, if i call “FileService.checkFile(‘topnews’)” it will always return undefined because “window.requestFileSystem” is asynchronous and returns before i can look if the file exists “filesystem.root.getFile(” to return the real result.

Hope here is a Cordova FileSystem expert :slight_smile:

A tutorial for FIleSystem usage: http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-requesting-quota


#2

you need to use promises or a callback in your service

 function (fileTyp) {
      var deferred = $q.defer();  
      window.requestFileSystem(window.PERSISTENT, 1024*1024, function(filesystem) {
       filesystem.root.getFile('/bpa_json/'+ fileTyp +'.json', {create: false}, 
          function() {
             deferred.resolve(true);
          },
          function() {
             deferred.reject();
          } );
      });
      return deferred.promise;
 }

Then in your controller, something like this…

 FileService.checkFile('topnews').then(function(){
        alert("FILE EXIST");
 }), function()  {
        FileService.createFile('topnews');
 });

This code is not tested… just wanted to get you started

Angular Promises


#3

Thx aaron​ksaunders,
i solve it with your idea.

Now i know Angular Promises :slight_smile:


#4

Glad it worked out, promises are everywhere now so it is best to wrap your head around the concepts as soon as possible. Hope you are building something great!!