Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async await with promises is then block required

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.

like image 856
fscore Avatar asked Sep 02 '25 09:09

fscore


2 Answers

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()
like image 135
Davi DeBarros Avatar answered Sep 04 '25 23:09

Davi DeBarros


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.

like image 31
nem035 Avatar answered Sep 04 '25 21:09

nem035