1

I have to get public ip addresses with a module called public-ip.

The doc says that for this to work as intended, it need to be asynchronous and work with promises.

My problem is that I need to extract the value after the asynchronous method is fulfilled and use it into a synchronous function.

Let consider this code :

import public_ip from 'public-ip'

function test() {
    public_ip.v4()
        .then((data) => {
            return data ;
        })
}
const ip = test() ;
console.log('Your ip is : ' + ip ) ;

and it returns:

Your ip is : undefined

Process finished with exit code 0

instead of returning my ip is xxx.xxx.xxx.xxx

but when I console out , with this minor change :

import public_ip from 'public-ip'

   function test() {
        public_ip.v4()
            .then((data) => {
                console.log (data) ;
            })
    }
    test() ;

it returns my ip. Now I understand that with promise the data processing have to happen within the async method like the following :

.then((data) => {
 //... data processing here ...
})

but is there a way to extra the data after the event loop closes and process it in a synchronous way ?

Thanks for helping out.

  • *"but is there a way"* – No. – deceze Dec 05 '18 at 07:52
  • *"is there a way to extra the data after the event loop closes and process it in a synchronous way ?"* You can only access the resolved value of a promise inside a `.then` callback. There is rarely a reason code needs to execute completely synchronously. It's usually easy to refactor the code so that any code that needs to access a promise value is inside a function. – Felix Kling Dec 05 '18 at 07:53
  • okay but is there a way get the async method to return a value I can use in the `console.log` method outside the async function ? – Rita Takahashi Dec 05 '18 at 07:55
  • No. N. O. It's about *timing*. An asynchronous value is by definition only available *sometime later*. You simply *cannot* have it **now**, you will need to wait for it. – deceze Dec 05 '18 at 07:57
  • The async function can return the promise: `function test() { return public_ip.v4();}` and then `test().then(data => console.log(data))`. But you cannot make the function magically return the unwrapped promise. A popular analogy: You cannot eat the pizza before it was delivered. – Felix Kling Dec 05 '18 at 07:58

0 Answers0