gpt4 book ai didi

javascript - 火狐操作系统 : return array using device storage api

转载 作者:行者123 更新时间:2023-12-02 18:31:02 24 4
gpt4 key购买 nike

我刚刚开始为 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.onsuccess中,您告诉firefox操作系统在取回文件时将其追加到您创建的数组中。这里重要的是,这不会立即发生,它会在未来的某个时候发生。

  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

关于javascript - 火狐操作系统 : return array using device storage api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com