【发布时间】:2021-04-21 09:21:30
【问题描述】:
我的 React Native 客户端代码中有以下 .then 示例链,目前没有 .catch,因为我正在寻找有关如何设置它的建议:
await getUserInfo(userId, JSON.stringify(ratingsQueryRatingType), 1)
.then(async userRatingData => {
await findMatchHistory(userId, '', 3)
.then(async matchHistoryData => {
这些函数调用我的 NodeJS 服务器。然后 NodeJS 服务器发回数据。
我正在尝试找出如何有效地将错误从服务器发送回客户端,并让客户端中的 .catch 部分处理该错误(例如使用 Alert.alert(error))。
我试图在我的服务器上引发如下错误,但随后在我的服务器上我收到未处理的承诺拒绝。它似乎没有将错误发送回客户端。
// Other code before this part
if (response==='Success') {
return res.status(200).json({'status': 'success'})
} else {
throw 'Match record was not confirmed successfully'
}
或者通常的做法是从服务器发送响应对象(而不是错误),然后使用某种 if 语句在客户端处理这些对象,如下所示?
if (results['status']==='success') {
// Code
} else if (results['status']==='failure') {
// Code
}
我确实读过 .then 与 .catch 链接是一个有吸引力的选择,所以感觉这不是正确的解决方案..
【问题讨论】:
-
我建议不要像这样将 async/await 与 .then 混合。
-
如果您的服务器上没有可以捕获它的中间件,您不能只使用
throw。在某些时候,您必须向客户发送一些东西。通常这类似于res.status(200).json({status: 'processing error'})或res.status(400).json({status: 'input error'})或res.status(500).json({status: 'unexpected internal error'})。然后,您需要在客户端破译它,在那里您可以拒绝带有错误消息的承诺。 -
感谢您的回复。 @Bergi 好的,服务器部分就解决了。只剩下客户端部分
-
@jonrsharpe:你能详细说明一下吗?也许这对你来说很明显,但对我来说这个话题还不清楚
-
例如第一部分变成
const userRatingData = await getUserInfo(...);。或者你可以从普通回调中返回承诺,而不是嵌套异步回调,每个回调等待一件事并且什么都不返回。现在你有两全其美。请参阅developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…、developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。
标签: javascript node.js react-native try-catch