1

I am working on the router-os library of mikrotik routers. I'm having trouble displaying a call to the API outside the callback. The foo variable should contain the object recover in the API only I can not get around the asynchronization problem

var MikroNode = require('mikronode-ng2');

const USER = "sofian";
const PASSWD = "sofian"

var toto;

var connection = MikroNode.getConnection('10.0.0.1', USER, PASSWD)

connection.connect(function (conn) {
    var chan = conn.openChannel();
    conn.closeOnDone = true;
    chan.write('/ip/address/print', function () {
        chan.closeOnDone = true;
        chan.on('done', function (data) {
            var parsed = MikroNode.parseItems(data);
            toto = parsed
            parsed.forEach(function (item) {
                console.log('Interface/IP: ' + item.interface + "/" + item.address);
            })
        })
    })
})

console.log(toto);

return to terminal :

undefined
Interface/IP: Lan/10.0.0.1/8
Interface/IP: Wan Orange/192.168.1.254/24

Thanks

EDIT with Promise :

I try it but it still does not work

var MikroNode = require('mikronode-ng2');

const USER = "sofian";
const PASSWD = "sofian"

var connection = MikroNode.getConnection('10.0.0.1', USER, PASSWD)
var result;

function test() {
    connection.getConnectPromise().then( function (conn) {
        conn.getCommandPromise('/ip/address/print').then(async function resolved(values) {
            // console.log('Addreses: ' + JSON.stringify(values));
            result = 'Addreses: ' + JSON.stringify(values)
            return await result;
        })
    })
}

console.log(test())

terminal :

undefined

I add async / await but it does not solve my problem

Sofian
  • 123
  • 1
  • 3
  • 11

1 Answers1

0

You cannot pull asynchronous data (such as data, parsed, etc) into a synchronous context. Think about it: By passing a callback to connection.connect() you're telling it "call this function at some indeterminate time in the future, when you're done connecting" and then the code continues immediately and hits console.log(toto) relatively way before the callback has executed. There is no way for data created in that callback to travel back in time.

If you want to write asynchronous code as though it were synchronous, use async/await - the library you're using does seem to support promises, so you'd have to use those functions instead to do it that way.

Klaycon
  • 10,599
  • 18
  • 35