英文:
How to async/await in onPress confirmation Alert?
问题
我需要在用户确认警告后删除一个帐户。
我尝试直接在确认按钮的onPress上使用async/await,但我收到一个错误可能未处理的Promise拒绝 (id: 0):。
const DeleteAccount = () => {
  Alert.alert(
    "删除帐户",
    "如果您删除帐户,您将失去当前的数据",
    [
      {
        text: "取消"
      },
      {
        text: "删除",
        onPress: async() => await deleteteUserApi(auth),
      }
    ],
    {
      cancelable: false,
    }
  )
}
<List.Item
  title="删除我的帐户"
  description="永久删除帐户"
  left={(props) => <List.Icon {...props} icon="delete" />}
  onPress={DeleteAccount}
/>
英文:
I need to delete an account when user confirms the Alert.
I tried using async/await directly to the confirm onPress but I receive an error Possible Unhandled Promise Rejection (id: 0):
const DeleteAccount = () => {
  Alert.alert(
    "Delete account",
    "If you delete your account, You will lose your current data",
    [
      {
        text: "Cancel"
      },
      {
        text: "Delete",
        onPress: async() => await deleteteUserApi(auth),
      }
    ],
    {
      cancelable: false,
    }
  )
}
<List.Item
  title="Delete my account"
  description="Delete account permanetly"
  left={(props) => <List.Icon {...props} icon="delete" />}
  onPress={DeleteAccount}
/>
答案1
得分: 2
可以在Alert的onPress选项上使用async函数。看起来问题可能来自函数本身。尝试捕获错误以查看发生了什么:
// ..
onPress: async () => {
  try {
    await deleteteUserApi(auth)
  } catch (error) {
    console.error(error)
  }
}
// ..
英文:
It’s possible to use async fonction on the Alert onPress option.
Looks like the problem is coming from the function itself. Try to catch errors to see what’s happening:
// ..
onPress: async () => { 
  try {
    await deleteteUserApi(auth)
  } catch (error) {
    console.error(error)
  }
}
// ..
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论