FirefoxOS:使用设备存储api返回数组
FirefoxOS: return array using device storage api
我刚刚开始为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;
}
谢谢你的帮助!
您正在启动一个空阵列
你正在告诉firefox操作系统在设备上查找图片
然后在cursor.onsaccess中,您告诉firefoxos在返回文件时将其附加到您创建的数组中。重要的是,这不是马上发生的,而是在未来的某个时候发生的。
然后返回您创建的空数组。它是空的,因为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!");
});
相关文章:
- 在页面卸载时写入HTML5 FileSystem API存储
- javascript api,用于在第三方域上存储身份验证令牌
- Chrome存储API无法使用内容脚本
- 如何将Facebook Graph API响应存储为Javascript数组
- 如何使用 github api 查找最新的存储库
- 围绕web存储的Javascript API包装器
- html5文件api,将用户选择的目录存储在sessionStorage中
- 如何存储推特搜索API推文并转发它们
- 正在尝试上载使用HTML5Fileneneneba API存储的文件
- 确定何时完成 JavaScript Dropbox 数据存储 API 的插入
- 使用 chrome 存储 API 从本地存储中存储和检索数据
- FirefoxOS:使用设备存储api返回数组
- Firefox插件sdk:如何在内容脚本中使用简单存储API
- 如何从chrome扩展's存储api访问多个键
- 在HTML5 LocalStorage中存储API凭据
- 变量won't在chrome应用中使用chrome存储API更新
- 哪个(如果有的话)Javascript存储API (Google Drive, Dropbox, OneDrive)提供
- 相当于无需重启的firefox扩展的简单存储API
- chrome扩展存储api获胜't设置数组
- 在chrome存储API集合调用中使用的密钥是否可以是变量