简体   繁体   English

如何正确使用try / catch,promise catch和async功能?

[英]How to use try/catch, promise catch and async function correctly?

This is how my upload function looks like at the moment. 这就是我目前的上传功能。 I'm using apollo mutation in that to upload a file. 我正在使用阿波罗突变来上传文件。

I do not understand how to use try/catch and catch of the promise (which client.mutate() is) correctly. 我不明白如何正确使用try / catch和catch的承诺( client.mutate()是)。 Also I declared the upload function as async . 我也宣布上传功能为async

So I guess I'm mixing some things up :-( 所以我想我正在把一些事情混在一起:-(

How do I catch errors correctly? 如何正确捕获错误?

Do I need both catches? 我需要两个渔获吗? Shouldn't I replace try/catch if I'm using a async function? 如果我使用异步功能,是否应该替换try / catch?

export default async function upload (client) {
  try {
    return client.mutate({
      mutation: uploadsMutation
    }).catch(err => {
      console.error(err)
    })
  } catch (error) {
    Alert.alert('Error', 'Could not upload files')
  }
}

async and await have to be used hand in hand - meaning nothing is automatically 'awaited' without using the await keyword. async使用asyncawait意味着不使用await关键字就不会自动“等待”任何内容。 In your example you're just returning the Promise returned from client.mutate . 在您的示例中,您只是返回从client.mutate返回的Promise。

export default async function upload (client) {
  try {
    return await client.mutate({
      mutation: uploadsMutation
    });
  } catch (error) {
    Alert.alert('Error', 'Could not upload files')
  }
}

Bear in mind your upload function is also returning a Promise by being async . 请记住,您的upload功能也会通过async返回Promise。 So calling code should handle it appropriately. 因此,调用代码应该适当地处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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