1

I am running this async function:

async function getIngress(namespace) {
  try {
    const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
    return result.body.items[0].spec.rules[0].http.paths[0].path;
  } catch (e) {
    console.error(e.response.body);
  }
}
console.log(getIngress(argument);

The console log only prints a promise. Is there a way I can access the returned value of the promise outside of a function like I am trying to?

Sheen
  • 586
  • 10
  • 22

3 Answers3

5

Yes, you can! I'll give you three ways:

Using async function

async function logPromiseResult() {
  console.log(await getIngress(argument));
}

Using .then callback

getIngress(argument).then(result => console.log(result));

Or you just can change that function definition

async function getIngress(namespace) {
    let response;
    try {
        const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
        response = result.body.items[0].spec.rules[0].http.paths[0].path;
    } catch (e) {
        console.error(e.response.body);
    }
    console.log(response);
    return response;
}

Hope that this is what you need and it helps you!

fguini
  • 326
  • 1
  • 5
2

await should work.

console.log(await getIngress(argument));
Radu Diță
  • 13,476
  • 2
  • 30
  • 34
1

1) getIngress(argument).then(console.log)

or the same: getIngress(argument).then(res => console.log(res))

2) await getIngress(argument), but it works only inside async function:

you should make async IIFE if your outside function isn't async or it is top level:

(async () => {
  console.log(await getIngress(argument))
})();
crystalbit
  • 664
  • 2
  • 9
  • 19