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

FirefoxOS: return array using device storage api

本文关键字:存储 api 返回 数组 FirefoxOS      更新时间:2023-09-26

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

谢谢你的帮助!

图片枚举是一个异步调用。从本质上讲,代码中发生的事情是:
  1. 您正在启动一个空阵列

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

  3. 然后在cursor.onsaccess中,您告诉firefoxos在返回文件时将其附加到您创建的数组中。重要的是,这不是马上发生的,而是在未来的某个时候发生的。

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

在某个时间点之后,将调用onsuccess函数。等待阵列完全填充的一种方法是在之后添加一个检查

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

当然,您的代码必须进入getImageFromDevice函数内部。您还可以将回调函数传递到getImageFromDevice函数中。

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

问题在于您正在使用的调用的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!");
});