1

I'm trying to use a package called public-ip but when I use the example on the github I can't use the variables outside of the async code

I have tried various solutions by making functions

function GetAddress() {
    return await publicIp.v4()
}

but these just return a Promise and I have tried to google on how to not get a promise / get the IP out of it but without any luck.

Any help is appreciated

KibbeWater
  • 174
  • 1
  • 10
  • 1
    At the top level you will have to deal with the promise one way or the other. If you show us how you intend to use the value we can make suggestions for how to structure your code. In your example, if you wrote `function GetAddress() { return publicIp.v4(); }` then you could use it as `getAddress().then(ip => {/* do something with ip here */})`. – Felix Kling Jul 18 '20 at 11:58
  • 2
    It's an async function you'll always have to go through async await or use promise. – Melchia Jul 18 '20 at 12:03
  • I want to do something like this: var connectionAddress = GetAddress() + port; – KibbeWater Jul 18 '20 at 12:04
  • 1
    That is not possible. Read here why and what to do instead: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CherryDT Jul 18 '20 at 12:17

2 Answers2

0

A .then() might fix your problem:

publicIp.v4()
  .then(ip => {
    // ip is the value, do your logic here
    console.log(ip)
  })
  .catch(error => {
    // if it throws an error, you can catch it and suppress it here
    throw error;
  });

See Promise.then() on MDN

Jabster28
  • 177
  • 11
-1

Define an async function and use it like this:

async function GetAddress () {
    return await publicIp.v4();
}

GetAddress()
    .then( address => {
        console.log(address);
    });

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
crosen9999
  • 823
  • 7
  • 13