Traditionally, you can use a callback pattern like so
function testZ(cb) {
var entireFile = document.getElementById("input").files[0];
var reader = new FileReader();
reader.readAsText(entireFile, "UTF-8");
reader.onload = function (e) {
var rawLog = reader.result;
cb(rawLog);
};
}
testZ(contents => {
// contents accessible here
})
Alternatively, you can make the code look more like synchronous code using Promises and async/await
function testZ() {
return new Promise((resolve, reject) => {
var entireFile = document.getElementById("input").files[0];
var reader = new FileReader();
reader.readAsText(entireFile, "UTF-8");
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
};
(async() => {
const contents = await testZ();
// contents accessible here
})();
Note: the asynchronous IIFE would not be required if you are in a function, just make that function async
- with the usual caveats that the function now returns a Promise, so don't expect syncrhonous results from it
async someFunction() {
const fileContent = await testZ();
// contents accessible here
}
Also, top-level await is available in modules
- so, no need to have an async
function at all in this case - simply:
const fileContent = await testZ();
// contents accessible here