0

I have a global var var imageURL = jQuery.Deferred(); as a deferred object.

Next I have a function that runs through a loop, and for each loop I intend to get the value that is produced through an asynchronous function. The problem I had was that I couldnt get the values properly as they were being called before the function had returned their value, so I was told to use jQuery deferred. Can't quite get my head round it:

    downloadProductImage: function(remoteImage, localImageName){

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
         fileSystem.root.getFile(localImageName, {create: true, exclusive: false}, function ff1(fileEntry) {
         var localPath = fileEntry.fullPath;
         var ft = new FileTransfer();
         ft.download(remoteImage,
              localPath, function (entry) {
                   imageURL.resolve(entry.fullPath);

                    //return entry.fullPath;

                     }, fail);
                   }, fail);
        }, fail);
}

The downloadProductImage function is executed in a loop, and just after this function is called I wish to get the value of the imageURL.resolve(entry.fullPath), so I did this:

    //start loop
    imageURL.done(function(theURL){
        alert(theURL);
    });
//end loop

If I understand this correctly, the callback from the file download is ran, and when completed the imageURL.done() is executed. But the done() keeps showing the same file path, as if it is overwriting each one.

Any help would be appreciated.

JamesG
  • 2,018
  • 2
  • 28
  • 57
  • Are you trying to resolve the same deferred object more than once? deferred objects can only be resolved once. – Kevin B Feb 12 '13 at 15:03
  • Yes I am doing that, didnt realise you could only defer one object. What would be a suitable workaround? – JamesG Feb 12 '13 at 15:05
  • In your case, it would make more sense to instead use either a custom event, or the `$.Callbacks` object. – Kevin B Feb 12 '13 at 15:08

1 Answers1

0

As said in comments, you can't use imageURL as a global var. $.Deferred can only be used once. When its state has been resolved or rejected, every time you will add .done or .fail callback, thet will immediatly return with the same result.

What you should do is remove your global imageURL, and make downloadProductImage returning a new $.Deferred. This way you can add a .done to the returned $.Deferred.

downloadProductImage: function(remoteImage, localImageName) {
    var imageURL = $.Deferred();
    window.requestFileSystem(
        [...]
        ft.download(remoteImage,
            localPath, function (entry) {
                imageURL.resolve(entry.fullPath);
                //return entry.fullPath;
                }, fail);
            }, fail);
    }, fail);
    return imageURL;
}

And don't forget to reject your deferred if your file transfert fails.

Mordhak
  • 2,646
  • 2
  • 20
  • 14