Issue
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?
Solution
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;
}
}
Answered By - Anıl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.