0

I’m new in JS, I have a problem with my code:

tbotping();

function tbotping () {
  var MikroNode = require('mikronode');

  var device = new MikroNode('IP');

  //device.setDebug(MikroNode.DEBUG);

  device.connect()
.then(([login])=>login('username','password'))
.then(function(conn) {
  
  conn.closeOnDone(true);
  
  var ping = conn.openChannel();
  ping.closeOnDone(true);
  console.log('Get ping');
  ping.write('/ping',{'address':'77.88.8.8','count':'3'});

  ping.data
  .subscribe(function (data) {
  var myJSON = JSON.stringify(data);
  console.log(myJSON);

    });
  });
};

The code works correctly, but I can’t understand, how can I get data from myJSON for return from main function to use. Now I can only see json data in console.

imPPLs
  • 1
  • 2
  • 2
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Robert Kawecki Nov 11 '21 at 17:45
  • You can't, because the data that will arrive later on (after the ping was completed) can't time-travel back to when the function returned. The whole code (including your main function) needs to be converted to be asynchronous. – CherryDT Nov 11 '21 at 18:48
  • Thx guys! If someone could help make my code to asynchronous, I would be very grateful! – imPPLs Nov 11 '21 at 19:05

1 Answers1

0

If someone could help make my code to asynchronous

You need to encapsulate your content of function tbotping() in a Promise object like :

function tbotping() {
    return new Promise(function (resolve, reject) {
        //Your previous code
    });
};

resolve parameter is a function. It is used to return result for an asynchronous function. In your case you need to return myJSON data. So you just need to add this line of code after console.log(myJSON) :

resolve(myJSON);

reject parameter is a function too. It is used to throw an occurred error for example when something bad appears on device.connect(). We will use it later.

Then, how main process can retrieve value of myJSON which is returned by resolve? Actually, tbotping() return a Promiseobject now. This object has a method called then(). When this method is called, all content of Promise is executed and we can retrieve the myJSON data via this code :

tbotping().then(function(myJSON) {
    //Use myJSON
})

You can notice that :

device.connect()
    .then(([login])=>login('username','password'))

uses Promise mechanism too. Actually, there is another method catch() which allows to retrieve error from reject function. Your code becomes :

tbotping().then(function(myJSON) {
    //Use myJSON
}).catch(function (error) {
    //Use error
});

And because device.connect() can potentially has error you can throw it like :

device.connect()
    .then(([login])=>login('username','password'))
    .then(function(conn) {
        //Code
    }).catch(function(error) {
        reject(error);
    });

But it is awkward to manage then() and catch() every time. To simplify, you can use combo async/await. First we need to tell JS that function(resolve, reject) is an asynchrone function by adding async keyword :

return new Promise(async function (resolve, reject) {

For each then(), you replace it by await :

/*

This code :

device.connect()
.then(([login]) => login('username', 'password'))
.then(function (conn) {
    //Code
})

becomes :
*/

const [login] = await device.connect();
conn = await login('username', 'password');

and

/*

This code :

tbotping().then(function(myJSON) {
//Use myJSON
});

becomes :
*/

const myJSON = await tbotping();

For each catch(), you replace it by try catch JS syntax. So, your final code becomes :

const MikroNode = require('mikronode');

function tbotping() {
    return new Promise(async function (resolve, reject) {
        try {
            const device = new MikroNode('IP');

            const [login] = await device.connect()
            const conn = await login('username', 'password');
            conn.closeOnDone(true);

            const ping = conn.openChannel();
            ping.closeOnDone(true);
            console.log('Get ping');
            ping.write('/ping', { 'address': '77.88.8.8', 'count': '3' });

            ping.data
                .subscribe(function (data) {
                    const myJSON = JSON.stringify(data);
                    resolve(myJSON);
                });
        } catch (error) {
            reject(error);
        }
    });
};


(async function() {//We need to create an anonymous function because await can be only runned in asynchrone bloc code
    try {
        const myJSON = await tbotping();
        console.log(myJSON);
    } catch (error) {
        console.error(error);
    }
})();//And don't forget to call the anonymous function by terminate it with "()"

Yes, it is more difficult to understand but you need to practice and check on the internet what are Promise, async and await. ^^

  • Thank you very much! You are my hero! This promise, async and await very hard to understand, but now i can do it! – imPPLs Nov 13 '21 at 09:32