Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

javascript - node function calling another function and returns undefined

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.

question from:https://stackoverflow.com/questions/65885835/node-function-calling-another-function-and-returns-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...