0

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. Also I declared the upload function as 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?

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')
  }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

2

async and await have to be used hand in hand - meaning nothing is automatically 'awaited' without using the await keyword. In your example you're just returning the Promise returned from client.mutate.

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. So calling code should handle it appropriately.

Flowers4Life
  • 151
  • 5
  • 1
    FWIW you don't have to use `await` inside an `async` function. Returning the promise directly would be fine, but of course then `try...catch` doesn't work and there wouldn't be a point in making the function `async`, but it is "ok" to do that. – Felix Kling Apr 30 '18 at 17:04
  • You're absolutely right, I commonly make `async` functions just to denote that they return a promise, potentially being generated further down. Edited the answer the clarify that. – Flowers4Life Apr 30 '18 at 17:10
  • Do I understand you correctly, that I should just directly return the promise and run try/catch at the place where I call the upload function? – user3142695 Apr 30 '18 at 17:44
  • You _can_ if that seems appropriate to your usage. Your example dealt with handling it directly in the `upload` function. If you do that, calling code will need to `await upload(client);`. – Flowers4Life Apr 30 '18 at 17:54