I am trying to get a return value from a function, but all I get is 'undefined'. I would guess its due to the order in which JS executes the functions, but first let me present a shortened version of the code:
// Analyzing Jenkins log
function analyseRawLog(callback) {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
callback(this.responseText);
} else if (this.readyState === 4) {
console.log("Failed to get raw console output.");
}
};
xhttp.open("GET", "consoleText", true);
xhttp.send();
}
// Takes as a parameter the output ofthe console, which
// is parsed from previous function
function analyseMetricsLog(consoleOutput) {
let analysisArray = [];
console.log("Analysing logs...");
// A for loop regexing the console output
// Results are appended in the array, which I return in the end
return analysisArray
}
// initiating the function on the page
analyseRawLog(analyseMetricsLog)
So far, it works as intended (because I use console.log for each information I parse). However, I want to add an extra UI in Jenkins page, which contains this information. This is why I added this analysisArray
, which contains all information. I plan to add this array in another function, which visualises the information in the Jenkins UI. This is a simplified version of what I tried to do:
function analyzeUI(){
// skipping the unimportant UI stuff
let results = []; // creating an array to contain the results
results = analyzeRawLog(analyzeMetricsLog) // I want to get the return value of
// the function, so I output it in
the UI
}
However, if I try to console.log(results)
, I will get undefined, which I guess it's due to the function executing after this. I tried a couple of solutions, but none of them seem to work:
1) Making a nested callback:
function analyseMetricsLog(consoleOutput, callback)
And in the end of the .js file:
analyseUI(analyseRawLog(AnalyzeMetricsLog))
I tried to get the callback value in my UI function, but it says that callback is not a function.
2) I tried using async
and await
, which I have never used before, but
the result was the exact same.
Could you please give me any tips how to get this return value?