phonecap同步调用文件系统 [英] phonecap synchronous call to filesystem
问题描述
我在使用phonegap进行异步调用时遇到问题,因为我需要获取以下函数的返回值才能处理其余代码.
I encounter a problem with asynchronous call using phonegap, because I need to get the return of the following function in order to process the rest of the code.
所以我有以下功能:
function getFileContent(fileName) {
var content = null;
document.addEventListener("deviceready", function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile("data/" + fileName, null, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
content = evt.target.result;
alert(content);
}
reader.readAsText(file);
});
}, fail);
}, fail);
}, false);
return content;
}
但是当我先尝试alert(getFileContent(fileName));
时,我会得到null
,然后是带有文件内容的警报
but when I try alert(getFileContent(fileName));
first I get null
and then the alert with the content of the file
我尝试在返回之前添加以下行,但是什么也不执行:
I have try to add the following line before the return but then nothing is executed:
while (content == null);
我想避免使用setTimeout
之类的东西,因为我需要立即获得响应,而无需延迟
I would like to avoid using something like setTimeout
because I need to get the response immediately and not after a delay
推荐答案
正如SHANK所说,我必须在最后一个回调函数中调用final函数,因此我只是将函数更改为:
As said by SHANK I must call the final function in the last callback function so I just changed my function to:
function getFileContent(fileName, call) {
var callBack = call;
var content = null;
var args = arguments;
var context = this;
document.addEventListener("deviceready", function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(
fileSystem) {
fileSystem.root.getFile("data/" + fileName, null, function(
fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
args = [].splice.call(args, 0);
args[0] = evt.target.result;
args.splice(1, 1);
callBack.apply(context, args);
}
reader.readAsText(file);
});
}, fail);
}, fail);
}, false);
}
现在可以正常工作了
这篇关于phonecap同步调用文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!