0

I'm trying to understand how promises and the async-await stuff work and I built the following code to get the list of connected devices on the computer but it returns 'undefined'.

var iosDevice = require("node-ios-device");

const the_action = () => {
  iosDevice.devices(function (err, devices) {
    if (err) {
      console.error("Error!", err);
    } else {
      return devices;
    }
  });
}

const create_promise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(the_action()), 100);
  });
};

const the_devices = create_promise();

const resolvePromise = (promise) => {
  promise
    .then((result) => console.log(result))
    .catch((error) => HTMLFormControlsCollection.log(error));
};

resolvePromise(the_devices);

I'm running the above script from terminal using node:

$> node the_script.js

What am I'm doing wrong or missing?

Thank you in advance

1 Answers1

0

the_action isn't returning anything. Your return statement simply returns from the iosDevice.devices callback - but the containing function doesn't return anything. That's where your problem lies. If you get the_action to return something, it will bubble up through your promise resolution and end up getting console.logged

mhodges
  • 10,938
  • 2
  • 28
  • 46
  • Thank you for your answer, updating the code as per your suggestion: `let conn_dev; const the_action = () => { iosDevice.devices(function (err, devices) { if (err) { console.error("Error!", err); } else { conn_dev = devices; } }); return conn_dev }` leads to the same 'undefined' result – viking_biking May 11 '21 at 21:01
  • @viking_biking That must mean that your iosDevices.devices call is asynchronous, in which case, refer to the question that was flagged as a duplicate for how to return a value from an asynchronous call. – mhodges May 11 '21 at 21:12
  • 1
    Yes!, finally, 'How do I return the response from an asynchronous call?' question gave me the clues to resolve my issue. Thank you so much! – viking_biking May 12 '21 at 01:15