Skip to content Skip to sidebar Skip to footer

How Do I Get A Variable To Exist Outside Of This Node.js Code Block?

I'm new to node.js and I've been trying like hell to wrap my head around how to use it. Within this, resp logs just fine with a lot of data. Outside this, mydata is undefined. I ca

Solution 1:

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


Post a Comment for "How Do I Get A Variable To Exist Outside Of This Node.js Code Block?"