简体   繁体   中英

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.

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.

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() 

class AsyncStorageHelper {

  static async getItem(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
  }
}

try {
  const result = await AsyncStorageHelper.getItem("logins")

  if (result)
    (result === "1") ? navigate(SCREEN1): navigate(SCREEN2)

} catch(err) {
  navigate(LOGINSCREEN)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM