Your function is asynchronous. That means the this.get_json()
call just starts the operation and then your Javascript execution continues. Then, sometime LATER when the networking response comes back, it calls the callback function.
As such, the ONLY place you can use the response is inside the callback. You can call another function from inside the callback and pass it the data, but you cannot use the data in code after your function.
this.get_json((_servers[i].ip + "/job/" + _servers[i].job + "/lastCompletedBuild/testReport/api/json"), function (resp) {
// use the response here
console.log(resp);
// or call some other function and pass the response
someOtherFunc(response);
});
// you cannot use the response here because it is not yet available
This is referred to as asynchronous programming and is a core tenet of node.js programming so you must learn how to do it and must adapt your programming style to work this way when using asynchronous operations that return their results via an asynchronous callback. This is definitely different than purely sequential/synchronous programming. It is something new to learn when using node.js.
There are more advanced tools for programming with asynchronous responses such as promises that are particularly important when trying to coordinate multiple asynchronous operations (sequence them, run them in parallel and know when all are done, propagate errors, etc...).
You may find these related answers useful:
Node.JS How to set a variable outside the current scope
Order of execution issue javascript
How to capture the 'code' value into a variable?
Nodejs Request Return Misbehaving