How to basically async await properly? I have created a helper for AsyncStorage which async awaits automatically but do the users of this also have to use async await
or promise approach to get the value?
This code works but unable to use the syntax correctly.
here is my code:
class AsyncStorageHelper {
static getItem = async (key: string) => {
let value: any = "";
try {
value = await AsyncStorage.getItem(key);
} catch (error) {
console.log(`Error item: ${value}`);
throw new Error(`Error ${value}`);
}
return value;
};
}
AsyncStorageHelper.getItem("logins")
.then(result => {
if (result) {
if (result === "1") {
navigate(SCREEN1);
} else {
navigate(SCREEN2);
}
}
})
.catch(err => {
navigate(LOGINSCREEN);
});
How can I convert the AsyncStorageHelper
code to async await as depending on the result I want to navigate to different places.
await must be used inside a async function.
async function helper() {
try {
const result = await AsyncStorageHelper.getItem("logins");
if (result) {
if (result === "1") {
navigate(SCREEN1);
} else {
navigate(SCREEN2);
}
}
} catch (error) {
navigate(LOGINSCREEN);
}
}
helper()
Async functions and promise-returning function can be used externally in the same manner.
AsyncStorageHelper.getItem("logins")
.then(result => {
if (result) {
if (result === "1") {
navigate(SCREEN1);
} else {
navigate(SCREEN2);
}
}
})
.catch(err => {
navigate(LOGINSCREEN);
});
Is the same as:
// note: this code must run in another async function
// so we can use the keyword await
try {
const result = await AsyncStorageHelper.getItem("logins");
if (result) {
if (result === "1") {
navigate(SCREEN1);
} else {
navigate(SCREEN2);
}
}
} catch (err) {
navigate(LOGINSCREEN);
}
Note: your code has an unknown code path. What happens when AsyncStorageHelper.getItem("logins")
returns a falsy value? You essentially have a noop and this might not be the desired behavior.
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