-2
const getNetwork = async () => {
        const status = await Network.getStatus();
        setStatus(status.connected);
        console.log(networkStatus);
        if (status.connected)
            return true;
        else
            return false;
}

How can I get back the value from getNetwork Function?

wentjun
  • 40,384
  • 10
  • 95
  • 107
Bryant Tang
  • 251
  • 3
  • 19
  • 3
    Does this answer your question? [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) – CertainPerformance May 05 '20 at 07:35
  • You `await` your call of `getNetwork()` - and await _that_ function, and so on and so on. `async`/`await` has a "viral" effect on programs and if you're unprepared it can cause large headaches. – Dai May 05 '20 at 07:35

2 Answers2

1

Pretty much the same way you would handle any other promised based functions

const res = await getNetwork();

or

getNetwork().then((res) => {
  // get response, handle the rest 
})
wentjun
  • 40,384
  • 10
  • 95
  • 107
-1

Async operations returns Promise objects. If you return a Promise from a function like in your example and pass it to a variable directly its type will be Promise. As a result you will be able to call then() and catch() methods on it.

const res = getNetwork();
res.then(
  (responseData) = doSomething();
)

But if you store the return value with await prefix, then it will return the resolved data

const res = await getNetwork();
console.log(res); // res will be equal responseData above

But you must be careful about errors, if it throws an error your code will crash. I personally prefer to encapsulate this process in a try-catch block and if I catch an error ı return a null value. Example code below

async getResponse(): Promise<object> { // object can be changed with your response type
  try {
    const res = await getNetwork();
    return res;
  } catch (e) {
    return null;
  }
}
Anıl
  • 54
  • 1
  • 8