There is no asynchronous issue, the ONLY issue with your code is that you declared allText in the scope of the onreadystatechange callback function
If you declare this var outside of that function, it will work just fine
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
var allText; // var declared in readTextFile scope
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return allText; // here you can return the data filled in above
}
Note however, that synchronous XMLHttpRequest in the main thread is deprecated in most browsers - you should learn to embrace asynchronous code. The easiest (and most cross browser currently) method is with callbacks, e.g.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true); // make it asynchronous
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
callback(rawFile.responseText);
}
}
}
rawFile.send(null);
}
usage
readTextFile('someFile.txt', function(allText) {
console.log(allText);
});
A note about CHROME
Chrome - without special command line flag --allow-file-access-from-files for now - will fail regardless, as it produces an error stating that "cross domain requests are only valid for http https ... etc" protocols ... file:/// isn't such a protocol
However, if you've opened the file using file:/// then how can reading a file:/// be cross domain??? Only the developers of Chrum can answer that one