Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returns promise object instead of value (async/await) [duplicate]

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.

like image 339
Lawris Avatar asked Feb 21 '18 14:02

Lawris


People also ask

Why is my async function returning a promise?

The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. So, async ensures that the function returns a promise, and wraps non-promises in it.

How do I use async await instead of promises?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Can you await a function that returns a promise?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.

Can a promise return an object?

Promise. resolve() method in JS returns a Promise object that is resolved with a given value.


1 Answers

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.

like image 53
samanime Avatar answered Sep 27 '22 18:09

samanime