FirefoxOS:使用设备存储API返回数组

时间:2013-07-22 12:25:02

标签: javascript firefox firefox-os

我刚刚开始使用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;     
            }

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

枚举图片是异步调用。基本上你的代码中发生了什么:

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

  2. 您正在告诉firefox操作系统在设备上查找图片

  3. 然后在cursor.onsuccess中,你告诉firefox os附加到你创建的数组,当它返回文件时。这里重要的是,这不会立即发生,它会在未来的某个时刻发生。

  4. 然后您将返回您创建的空数组。它是空的,因为onsuccess功能实际上并没有发生。

  5. 在某个时间点之后,将调用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

答案 1 :(得分:0)

问题在于您正在使用的呼叫的aSynchronous性质。

当你仍然为空时,你返回(并且可能正在使用)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!");
});