簡體   English   中英

從Javascript的嵌套函數中訪問變量

[英]Accessing a variable from within nested functions in Javascript

我有以下功能:

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

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

函數downloadProductImage()位於全局var app = {}中,因此可以通過app.downloadProductImage()訪問。

此函數在一個循環中運行,我希望返回imageURL但似乎無法獲取它。 我在var app = {}之外聲明了全局var = imageURL,但是每當我嘗試在另一個函數中獲取imageURL時,第一個循環返回的都是undefined,其余的都是正確的。

我不確定為什么第一次循環返回未定義。var imageURL在頁面頂部全局聲明。

如果我在上面代碼中的// RETURN THIS imageURL = entry.fullPath;下警告(imageURL),則它會正確發出警報,而並非是我嘗試在函數外部訪問它時

鑒於提到的@dfsq這是一個異步調用,我相信當您在頂層訪問imageURL時,您會發現它未定義,因為還沒有調用回調。

最簡單的確認方法是在設置imageURL之前和之后在回調中插入兩個console.log()語句。 以及另外兩個console.log()語句,這些語句圍繞您訪問imageURL的頂級代碼中的點。

如果訪問確實發生在分配之前,那么這將解釋為什么您看到“未定義”。 為了解決您的問題,您需要將在頂層執行的操作推遲到回調完成之前。 jQuery Promise是執行此操作的一種方法,但其他庫中還有其他選項。 在所使用的任何庫中,將“未來”,“承諾”,“延期執行”作為關鍵字查找。 如果使用任何類型的事件框架,也可以使用:在回調中觸發事件,並在頂層監聽事件(確保在觸發之前先偵聽,否則會遇到相反的問題)。

如果您使用的是jQuery,則以下內容可能會助您一臂之力:

var imageURLPromise = jQuery.Deferred();

downloadProductImage: function(remoteImage, localImageName){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
        fileSystem.root.getFile(localImageName, {create: true, exclusive: false}, function(fileEntry) {
            var localPath = fileEntry.fullPath;
            var ft = new FileTransfer();
            ft.download(remoteImage,
                localPath, function(entry) {
                    // Note: The assignment is mediated by the DeferredObject that handles the timing issues for us.
                    imageURLPromise.resolve(entry.fullPath);
                }, fail);
        }, fail);
    }, fail);       
}   

imageURLPromise.done(function(imageURL) {
    // Use imageURL here at toplevel.
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM