0

i have the following code in nodejs:

const unifi = require('node-unifi');

const controller = new unifi.Controller(IP_ADDRESS, 8443);

function login(apiCall) {
  controller.login(USERNAME, PASSWORD, function (err) {
    if (err) {
      console.log('ERROR: ' + err);
      return;
    }
    apiCall();
  });
}

function getAllClients(site) {
  login(function () {
    controller.getClientDevices(site, (res, data) => {
      console.log(data);
    });
  });
}

getAllClients('siteid');

In original call, any function needs to be called within login() so it can only be called while logged in. When i call the function getAllCients(siteID) i get desired result in console.log. But for love of god I can't get the result returned from the function in another file where I required the said function. Always get undefined.

I assume I need to use a callback but after reading multiple forums (i.e. art of node) I am no wiser were to have the callback.

Any help would be appreciated.

Jakub Koudela
  • 160
  • 1
  • 18
  • 1
    [Convert an your callback API to promises](https://stackoverflow.com/q/22519784) and then [return the response from the asynchronous call](https://stackoverflow.com/q/14220321). You can also use more callbacks but promises are a lot easier to deal with. – VLAZ Jan 25 '21 at 13:41
  • hi, thank you for your quick answer. But could give me an example, please? Iam fairly new to this and its a bit confusing :-) – Jakub Koudela Jan 25 '21 at 14:49

1 Answers1

1

Thanks to @VLAZ who pointed me in the right direction :-)

my code after edit:

function getAllClients(site) {
  return new Promise(function (resolve, reject) {
    login(function () {
      controller.getClientDevices(site, (err, data) => {
        if (!err) {
          resolve(data);
        }
      });
    });
  });
}

all i changed was returning promise which i then consume in another file with .then()

Thank you!

Jakub Koudela
  • 160
  • 1
  • 18