问题
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.
So I have the following function:
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;
}
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);
I would like to avoid using something like setTimeout
because I need to get the response immediately and not after a delay
回答1:
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);
}
And now it's working
来源:https://stackoverflow.com/questions/18141841/phonecap-synchronous-call-to-filesystem