如何在按下确认警报时使用异步/等待?

huangapple go评论46阅读模式
英文:

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 = () =&gt; {
  Alert.alert(
    &quot;Delete account&quot;,
    &quot;If you delete your account, You will lose your current data&quot;,
    [
      {
        text: &quot;Cancel&quot;
      },
      {
        text: &quot;Delete&quot;,
        onPress: async() =&gt; await deleteteUserApi(auth),
      }
    ],
    {
      cancelable: false,
    }
  )
}
&lt;List.Item
  title=&quot;Delete my account&quot;
  description=&quot;Delete account permanetly&quot;
  left={(props) =&gt; &lt;List.Icon {...props} icon=&quot;delete&quot; /&gt;}
  onPress={DeleteAccount}
/&gt;

答案1

得分: 2

可以在AlertonPress选项上使用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 () =&gt; { 
  try {
    await deleteteUserApi(auth)
  } catch (error) {
    console.error(error)
  }
}
// ..

huangapple
  • 本文由 发表于 2023年2月24日 09:56:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定