Downloading multiple files file-transfer


#1

I am trying to make it work downloading of multiple files, but then i see the console output it is called so much times sometimes hangs and barely works, download few files.
At first tried with ngcordova file, is this implemented in it? i dont think so, so i created my own factory but i am not sure how to do it. My background is mostly programming with python, this async programming sometimes drive me nuts ;). Should be a common thing, any help appreciated.

.factory('FTransfer', function($timeout) {

    var filepathurl = 'file:///mnt/shared/productos/';

    'use strict';

    //function downloadFiles(fileurl, idproduct)
    function downloadFiles(filesinfo)
    {
            var ft = new FileTransfer();
            if (filesinfo.length > 0)
            {
                for (var i=0; i < filesinfo.length - 1; i++)
                {
                    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
                        console.log(JSON.stringify(filesinfo));
                        ft.download(
                        //self.fileTransfer.download(
                            encodeURI(filesinfo[i].imagen),
                            filepathurl + 'default-producto-' + filesinfo[i].product_id + '.jpg',
                            function(entry) {
                                console.log("download complete: " + entry.toURL());
                                filesinfo.pslice(i,1);
                                downloadFiles(filesinfo);
                            },
                            function(error) {
                                console.log("download error source " + error.source);
                                console.log("download error target " + error.target);
                                console.log("upload error code" + error.code);
                                console.log(JSON.stringify(filesinfo[i]));
                                downloadFiles(filesinfo);
                                /*if ( ( pfileindex = pendingIdProducts.indexOf(idproduct)) == -1)
                                {
                                    pendingIdProducts.push(idproduct);
                                } */
                                //volver a llamar a tomar archivo
                                //return callback('false');
                            },
                            false,
                            {
                                headers: {
                                    "Authorization": "Basic OElWSEtYM0FTESTTTTTTTTTTTTTTTTTT"
                                }
                            }
                        );
                        //downloadFiles(filesinfo);
                      });
                }
            } else
            {
                return;
            }
    }

    return {
        getFiles: function(filesurl) {
                downloadFiles(filesurl); 
        }
    };
})