8

I got this code using the async/await :

function _getSSID(){
   return new Promise((resolve, reject)=>{
      NetworkInfo.getSSID(ssid => resolve(ssid))
   })
}

async function getSSID(){
   let mySSID =  await _getSSID()
   if (mySSID == "error") {
     return 'The value I want to return'
   }
}

And getSSID() is equal to this : enter image description here

Looks like the getSSID() function will always return a promise. How can I get "The value I want to return" in plain text ?

Any help is greatly appreciated.

Lawris
  • 965
  • 2
  • 9
  • 21

1 Answers1

18

Declaring a function async means that it will return the Promise. To turn the Promise into a value, you have two options.

The "normal" option is to use then() on it:

getSSID().then(value => console.log(value));

You can also use await on the function:

const value = await getSSID();

The catch with using await is it too must be inside of an async function.

At some point, you'll have something at the top level, which can either use the first option, or can be a self-calling function like this:

((async () => {
    const value = await getSSID();
    console.log(value);
})()).catch(console.error):

If you go with that, be sure to have a catch() on that function to catch any otherwise uncaught exceptions.

You can't use await at the top-level.

samanime
  • 25,408
  • 15
  • 90
  • 139
  • While I hope top-level `await` never makes the cut (see [top-level `await` is a footgun](https://gist.github.com/Rich-Harris/0b6f317657f5167663b493c722647221)), it is currently [a stage 1 proposal](https://github.com/MylesBorins/proposal-top-level-await). – Patrick Roberts Feb 21 '18 at 15:02
  • 1
    Indeed. I've read that, and I tend to agree with the gist you linked. That's why I like the anonymous self-calling async function to kick things off. Still mostly at the top level, with the benefits of not really being there. – samanime Feb 21 '18 at 15:03
  • 3
    It doesn't actually solve my problem, I want to create a variable that will be equal to the value I want to return with the promise. – Lawris Feb 21 '18 at 15:35
  • It should. If `mySSID === 'error'`, then the `value` in all of the examples above will equal `"The value I want to return"` – samanime Feb 21 '18 at 15:47