phonecap对文件系统的同步调用

phonecap synchronous call to filesystem

本文关键字:同步 调用 文件系统 phonecap      更新时间:2023-09-26

我遇到了使用phonegap进行异步调用的问题,因为我需要获得以下函数的返回才能处理其余的代码。

所以我有以下功能:

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,然后是带有文件内容的警报

我试图在返回之前添加以下行,但没有执行任何操作:

while (content == null);

我想避免使用类似setTimeout的东西,因为我需要立即获得响应,而不是在延迟

之后

正如SHANK所说,我必须调用最后一个回调函数中的final函数,所以我刚刚将函数更改为:

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);
}

现在它正在上运行