Since node is primarily asynchronous and uses callbacks (as opposed to promises), you'd likely want to define a function that will be called that takes a parameter which is the output of your asynchronous call.
For example (in your case): you get courseName
in the callback for response.on('end', ...
. You could define a function such as:
function processCourseName(name) {
console.log('do something with', name);
}
And then after console.log('finished');
, just add a call to that method
...
courseName = ...
console.log("finished");
processCourseName(courseName); //whenever the request is finished, then process the course name in a separate function
More explanation: Your return courseName
statement are exiting from the function before the http.request
call is finished, and therefore before courseName
is even assigned to a proper value.
More edit: I took a look at the webot
module and it looks like its written in a way that doesn't support async code? Usually libraries pass a callback function you can call when your async processing is done, like function(info, callback) {}
, but webot
does not appear to. Your best bet might be to assign courseName
to the info
object (info.courseName
) you are given and notify your program to use courseName elsewhere.
Notes:
- You should use somthing like mikeal/request to make requests outwards, as it's written specifically to do so.