2013-02-12 90 views
0

我有一個全局變量var imageURL = jQuery.Deferred();作爲延遲對象。使用jQuery deferred()並在循環內的函數內解析

接下來我有一個函數,它貫穿一個循環,並且對於每個循環,我打算獲取通過異步函數生成的值。我遇到的問題是,我無法正確地獲取值,因爲它們在函數返回值之前被調用,所以我被告知使用延遲的jQuery。不能完全得到我的頭一輪是:

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); 
} 

的downloadProductImage功能在一個循環中執行,並且該功能被稱爲剛過我希望得到的imageURL.resolve的值(entry.fullPath)所以我這樣做:

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

如果我理解正確此,從文件下載回調跑去,當完成了imageURL.done()被執行。但done()不斷顯示相同的文件路徑,就像它覆蓋每個文件路徑一樣。

任何幫助,將不勝感激。

+0

您是否嘗試多次解析相同的延遲對象?延期對象只能解析一次。 – 2013-02-12 15:03:31

+0

是的,我正在那樣做,沒有意識到你只能推遲一個對象。什麼是合適的解決方法? – JamesG 2013-02-12 15:05:40

+0

就你而言,使用自定義事件或'$ .Callbacks'對象會更有意義。 – 2013-02-12 15:08:12

回答

0

正如評論中所說,你不能使用imageURL作爲全局變量。 $.Deferred只能使用一次。當其狀態爲resolvedrejected時,每次您將添加.done.fail回調時,它們將立即返回,結果相同。

你應該做的是刪除你的全局imageURL,並使downloadProductImage返回一個新的$.Deferred。這樣,您可以將.done添加到返回的$.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; 
} 

而且不要忘了你的reject如果你的文件transfert失敗推遲。