(1) retrieving a File object given a FileEntry
(2) reading the file contents from the File object
Let's start with (2):
function readFile(file) {
var reader = new FileReader();
waitfor(var evt) {
reader.onloaded = resume;
reader.readAsText(file);
}
return evt.target.result;
}
Notice how we declare 'evt' in the waitfor/resume's parentheses. This
parameter will automatically be bound when the 'resume' callback is
called.
Now (1):
function getFile(entry) {
waitfor(var rv, success) {
entry.file(function(file) { resume(file, true); },
function(err) { resume(err, false); });
}
if (!success) throw rv;
return rv;
}
Again, we declare the parameters returned through 'resume' in the
waitfor's parentheses. This time we need two parameters to distinguish
between the error case and the success case. In the error case, we
throw an exception.
With these two functions, you can now write synchronous code like this:
var file = getFile(entry);
var contents = readFile(file);
... do something with contents ...
For more waitfor()/resume examples, see e.g.
http://onilabs.com/presentations/ugent/suspend-events.html or
http://onilabs.com/presentations/ugent/retraction-xhr.html
Notice that the 'getFile' function above could be improved by adding
error handling and cancellation handling (the latter so that the file
read gets automatically aborted if the call is cancelled - see e.g.
the slides starting at
http://onilabs.com/presentations/ugent/cancellation.html ).
Cheers,
Alex
I guess it's clear from the sample I just posted, but just for completeness:
You need to arrange for 'onloaded' to call 'resume' (either by setting
onloaded=resume, or by calling resume(..) from within the callback you
assign to onloaded). As 'resume' is only defined within the
waitfor()'s curlies, you also need to move the reader.onloaded
assignment into that block. Finally, to extract parameters that are
being passed into 'resume', you declare them in the waitfor()'s
parentheses.
Cheers,
Alex