How to getTopics on JavaScript.
Hello, im completly new to JavaScript, but i did some research and i menage to print out on the console the alive topics, using this function.
function getTopics() {
var topicsClient = new ROSLIB.Service({
ros : ros,
name : '/rosapi/topics',
serviceType : 'rosapi/Topics'
});
var request = new ROSLIB.ServiceRequest();
topicsClient.callService(request, function(result) {
console.log("Getting topics...");
console.log(result.topics);
});
};
or even with this :
var ros = new ROSLIB.Ros({
url : 'ws://localhost:9090'
});
ros.getTopics(function(topics) {
console.log(topics.topics);
});
But when i add a return to the function it doesnt return , do you know why ? How can i get the topics in one global variable ?
First of all, I would like to point that calling this function getTopics could be a little confusing due to the fact that this is not a topic subscrition (here you can see a real topic subscription) this is a Client service call (and for what i see, I imagine that this service has an empty request message). If you need further information on what i say, just ask :)
Second, i am not quite sure which is the object you try to return and in which scope, so, if you could give us an example of the code, I think we could give you better feedback! Meanwhile, if you create a variable inside getTopics, let's say, before TopicsClient creation (var return_var;) the you assign the result value inside callService (return_var = result;) and returning the value JUST after closing the call service (return return_var;) theoretically, this should work.
And btw, if your main goal is to put the result into a global variable, you do not need write a return! just create return_var outside getTopics (and outside of its class, it it is part of a class) and it should work
that is my point, that doesn't work. If i do this
The output of the last print is undefined. i think its because of sync and unsynced stuff of javascript.
How you return the value from the topic? you are not explaining it yet. Locally my idea is like:
Lest gonna create first the ros variable in the global scope:
Then we define the function
Then in the global scope again
Directly in global you do the following way:
First create the global variable and ros variable:
Then you define the function without return and you assign the result into the global variable:
finally you just ask the function: