如何正确使用 try/catch、promise catch 和 async 函数?
How to use try/catch, promise catch and async function correctly?
这就是我的上传功能目前的样子。我正在使用 apollo 突变来上传文件。
我不明白如何正确使用 try/catch 和 catch of the promise(client.mutate()
是)。
此外,我将上传功能声明为 async
.
所以我想我混淆了一些东西:-(
如何正确捕获错误?
两个都需要吗?如果我使用的是异步函数,我不应该替换 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
和 await
必须一起使用 - 这意味着如果不使用 await
关键字,则不会自动 'awaited'。在您的示例中,您只是返回从 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')
}
}
请记住,您的 upload
函数也通过 async
返回 Promise。所以调用代码应该适当地处理它。
这就是我的上传功能目前的样子。我正在使用 apollo 突变来上传文件。
我不明白如何正确使用 try/catch 和 catch of the promise(client.mutate()
是)。
此外,我将上传功能声明为 async
.
所以我想我混淆了一些东西:-(
如何正确捕获错误?
两个都需要吗?如果我使用的是异步函数,我不应该替换 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
和 await
必须一起使用 - 这意味着如果不使用 await
关键字,则不会自动 'awaited'。在您的示例中,您只是返回从 client.mutate
.
export default async function upload (client) {
try {
return await client.mutate({
mutation: uploadsMutation
});
} catch (error) {
Alert.alert('Error', 'Could not upload files')
}
}
请记住,您的 upload
函数也通过 async
返回 Promise。所以调用代码应该适当地处理它。