0

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 can't figure out why that is, and was hoping someone could help me get the resp data out of the code block.

    var mydata = this.get_json((_servers[i].ip + "/job/" + _servers[i].job + "/lastCompletedBuild/testReport/api/json"), function (resp) {
        console.log(resp);
    });
    console.log(mydata)
  • That function isn't going to return into mydata. You'll need to set it elsewhere ( ideally not a global ) and set the value once the callback is fired from the get_json response. The most important thing to note here is that this is an async call, which is why you're registering a callback function to begin with. – Wedge Martin Nov 04 '15 at 00:19
  • `this.get_json(...)` returns undefined, so `mydata` will always be undefined. – Kevin B Nov 04 '15 at 00:22

1 Answers1

2

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

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you for taking the time to explain that! It's definitely a paradigm shift and I now see that I need to dig in deeper before 'tinkering'. Thank you very much – user1054583 Nov 04 '15 at 15:58