0

我刚刚开始为 FirefoxOS 编码,并试图获取目录中的文件列表。

这个想法是找到每个文件的名称并将其添加到数组中(这可行),但我想返回填充的数组,这就是我遇到的问题。似乎该数组在函数期间被填充(因为我可以让它从中吐出文件名)但是当我想将它返回给另一个函数时它似乎是空的?

这是有问题的功能:

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

谢谢你的帮助!

4

2 回答 2

2

枚举图片是一个异步调用。基本上你的代码中发生的事情是这样的:

  1. 您正在启动一个空数组

  2. 您是在告诉 Firefox os 在设备上查找图片

  3. 然后在 cursor.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 函数。

请参阅更好地理解 JavaScript 中的回调函数

于 2013-07-22T20:43:38.977 回答
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!");
});
于 2013-07-22T20:47:14.267 回答