2013-07-22 30 views
0

我刚开始使用FirefoxOS编码,并试图获取目录中的文件列表。FirefoxOS:使用设备存储API返回数组

想法是找到每个文件的名称并将其添加到数组(它的工作原理),但我想返回填充的数组,这就是我解开的地方。看起来数组在函数中被填充(因为我可以从中抽取文件名),但是当我想将它返回给另一个函数时,它看起来是空的?

下面是函数题:

function getImageFromDevice(){ 
    var imageHolder = new Array(); 
    var pics = navigator.getDeviceStorage('pictures'); 

    // Let's browse all the images available 
    var cursor = pics.enumerate(); 
    var imageList = new Array(); 
    var count = 0; 

    cursor.onsuccess = function() { 
    var file = this.result; 

    console.log("File found: " + file.name); 

    count = count +1; 

     // Once we found a file we check if there are other results 
     if (!this.done) { 

    imageHolder[count] = file.name; 

     // Then we move to the next result, which call the cursor 
     // success with the next file as result. 
     this.continue(); 

     } 
     console.log("file in array: "+ imageHolder[count]); 
       // this shows the filename   
       } 

    cursor.onerror = function() { 
     console.warn("No file found: " + this.error); 
    } 


      return imageHolder;  
      } 

感谢您的帮助!

回答

2

枚举图片是一个异步调用。基本上就是在你的代码的情况是这样的:

  1. 你正在发起一个空数组

  2. 你告诉火狐OS寻找图片在设备上

  3. 然后在光标。 onsuccess你告诉firefox os追加到你创建的数组当它恢复文件。这里重要的是,这不会马上发生,它发生在将来的某个时刻。

  4. 然后你正在返回你创建的空数组。它是空的,因为onsuccess函数并没有真正发生。

在某个时间点之后onsuccess函数将被调用。等到阵列的方法之一是全人口将在检查后添加:

if (!this.done) { 
    imageHolder[count] = file.name; 
    this.continue(); 
} 
else { 
    //do something with the fully populated array 
} 

但那么当然你的代码有去getImageFromDevice函数内。您还可以将回调函数传递给getImageFromDevice函数。

Getting a better understanding of callback functions in JavaScript

0

问题是与您正在使用的电话的异步特性。

imageHolder的值仍然是空的时候返回(可能是使用) - 因为对“onsuccess”函数的调用是延迟调用,它们会在稍后发生,而您的函数立即返回, )imageHolder值。

你应该做在这种情况下,类似的规定:

function getImageFromDevice (callback){ 

    ... 

    cursor.onsuccess = function() { 
    ... 

    if (!this.done) { 

     // next picture 
     imageHolder[count] = file.name; 
     this.continue(); 

    } else { 

     // no more pictures, return with the results 
     console.log("operation finished:"); 
     callback(imageHolder); 

    } 
    } 

} 

或者使用Promises在你的代码来完成相同的。

使用上述由例如为:

getImageFromDevice(function(result) { 
    console.log(result.length+" pictures found!"); 
});