0

Here's a function I'm writing to talk to an api using axios. I'm struggling with getting this function to return the an array. I understand that I get a promise out of this, but when I chain then() onto my function with the intent to use the data from the promise, it has nothing in it. I can put in a console.log(reqs) instead of the return value and it will print the data I'm interested in along with an 'undefined' line at the top, though I'm not quite sure why. I'm trying to avoid the use of console.log with the exception of testing my function where possible as I don't want this data viewable from the console.

Here is my function.

async function getMembers(omeIp,omeUser,omePass) {
    var reqs = [];
    axios({
        method: 'get',
        url: `https://${omeIp}/redfish/v1/Systems/Members`,
        auth: {
            username: omeUser,
            password: omePass
        },
        httpsAgent: new https.Agent({
            rejectUnauthorized: false
        }),
        headers: {'Self-Signed-Header': 'certificate'}
    }).then((res) => {
        value = res.data['value'];
        for(var key in value) {
            let member =  value[key]['@odata.id'];
            reqs.push(member);
        }
        return reqs;
    }).catch((err) => {
        console.log(err);
    });
};
module.exports = {
        getMembers,
};

and here is what I'm calling it with.

const {getMembers} = require('./functions.js');

var omeIp = "100.73.32.21",
    omeUser = "admin",
    omePass = "Sq%9A&pEBP";

getMembers(omeIp,omeUser,omePass).then((res) => console.log(res));

How do I get the result from my function to allow me to chain a then() onto the end and use the contents of the promise? or is there a better way to do this?

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • 1
    You need to return the value axios returns. `return axios...` – Felix Kling Dec 04 '18 at 21:30
  • What Felix says and remove the `async` form the function because you don't want to resolve your promise with a promise – Sebastian Speitel Dec 04 '18 at 21:34
  • Same as above, though note that there isn't really any harm is leaving the `async`, but it should be removed if `axios(...)` will _always_ return a promise, which in this case it will. It can be helpful to mark functions as `async` if you want to ensure they _always_ return a promise since sometimes you might have logic inside the function that returns non-promise values that you then want to wrap in a promise. – Matthew Herbst Dec 04 '18 at 21:36
  • @MatthewHerbst But wouldn't it be like `Promise.resolve(Promise.resolve())`? – Sebastian Speitel Dec 04 '18 at 21:38
  • Yes, in this case. There's not really any harm to that - one extra tick of the event loop. Sometimes it's worth that trivial overhead to make it clear to other devs that the function returns a Promise, especially if you aren't using JSDocs or types – Matthew Herbst Dec 04 '18 at 21:41
  • 1
    @MatthewHerbst Sorry, I didn't know Promises resolving to promises resolve to the resolved value of the inner Promise – Sebastian Speitel Dec 04 '18 at 21:51

1 Answers1

1

EDIT: Thank you to Sebastian for reminding me about the existence of Promise chaining. This answer is now much simplified.

.then() and .catch() are methods on a Promise object. To give the caller of your function access to them, all you need to do is return the Promise object created by axios:

function getMembers(omeIp, omeUser, omePass) {
  return axios({
    method: 'get',
    url: `https://${omeIp}/redfish/v1/Systems/Members`,
    auth: {
      username: omeUser,
      password: omePass
    },
    httpsAgent: new https.Agent({
      rejectUnauthorized: false
    }),
    headers: {
      'Self-Signed-Header': 'certificate'
    }
  }).then((res) => {
    const reqs = [];
    value = res.data['value'];
    for (var key in value) {
      let member = value[key]['@odata.id'];
      reqs.push(member);
    }

    return reqs;
  }).catch((err) => {
    console.log(err);
  });
};

You can then use your function like this:

getMembers(A, B, C).then(reqs => {
  // Do something with reqs if getMembers is successful
});
MTCoster
  • 5,868
  • 3
  • 28
  • 49