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 :
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.
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.
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.
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.
Promise. resolve() method in JS returns a Promise object that is resolved with a given value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With