I'm trying to define a funciton to check if a file exists, but the function always get undefined, even when it finds the file:
var findFile = function(startURL) {
var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
var uri = host + startURL + '/file.js';
//console.log(uri);
var http = new XMLHttpRequest();
http.open('GET',uri,true);
http.send();
var processRequest = function (e) {
if (http.status == 200) {
return "found";
} else {
console.log(http.status);
console.log(http.readyState);
return 'not_found';
}
}
http.onreadystatechange = processRequest;
}
Running for a valid file (that gets the 200 result from http), I get a undefined result.
a = findFile('/app');
>undefined
What am I doing wrong in return statement?
EDIT
I added the callback function, but I'm still getting undefined:
This is my code now:
var findServiceWorkerFile = function(startURL,callback) {
var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
var uri = host + startURL + '/RoasSDKWorker.js';
//console.log(uri);
var http = new XMLHttpRequest();
http.open('GET',uri,true);
http.send();
var file_status;
var processRequest = function (e) {
if (http.status == 200) {
file_status = 'found';
callback(file_status);
"found";
} else {
file_status = 'not_found';
callback(file_status);
}
}
http.onreadystatechange = processRequest;
}
function findFileCallBack(value) {
return value;
}