apaszke / tcp-ping

TCP ping utility for node.js
MIT License
123 stars 27 forks source link

How to return the data? #3

Closed sachethegde closed 7 years ago

sachethegde commented 7 years ago

Hello,

I have been trying to return the data. It works totally fine when I do console.log....but then I need to use the data for something else. Please find the code. Thanks.

pingTest(){ let msg= 'false'; tcpp.probe('www.google.com', 80, function(err, available) { return console.log(available); //msg=available; }); return msg; }

I see msg contains only 'false'.

Sparticuz commented 7 years ago

You are setting msg to false.

You want to return available or err, not msg

sachethegde commented 7 years ago

That works too. I want to return "available" or "err" from the function "pingTest". Please let me know.

apaszke commented 7 years ago

I think the problem might be that you're using let for msg and that declares it as an immutable variable. Try changing it to var.

sachethegde commented 7 years ago

I have tried var. As far as I read It is something to deal with Async functions. I have gone through them but unable to find the solution.

apaszke commented 7 years ago

Oh yeah of course. You're returning msg before the callback is called, so it doesn't even get a chance to be set. Add a console.log after you call ping and you'll see that it exits before. It is because of how async functions work. I'm closing that issue because it's not a bug.

sachethegde commented 7 years ago

Yes, of course, this was a question, not a bug report. Please let me know if you have a solution for this question. Thanks,

apaszke commented 7 years ago

You need your pingFunction to receive a callback, that's how async programming works. There are a lot of good tutorials on the internet, I'd really recommend you to read up on that.

pingTest(callback){
  tcpp.probe('www.google.com', 80, function(err, available) {
    return console.log(available);
    // do some processing here and pass the result to callback
    callback(err, available);
  });
}