【问题标题】:How to effectively .then chain on client with .catch?如何使用 .catch 有效地 .then 链接客户端?
【发布时间】: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


【解决方案1】:

我认为我们应该向客户端发送错误代码而不是发送消息,尽管您也可以这样做。您可以根据后端发生的错误检查状态码 -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

此外,在客户端,您可以使用拦截器并创建错误处理程序服务层,并根据您将发送到客户端的代码进行处理。您可以按照以下步骤为您的应用设置一个:https://bilot.group/articles/using-react-router-inside-axios-interceptors/

并且,在后端,如果出现错误,请尝试将其记录到服务器上的日志文件中。

// Other code before this part
if (response==='Success') {
    return res.status(200).json({'status': 'success'})
} else {
    res.status(based on what happened on server).json({'status': 'failure'})
}

对于.then channing,您应该使用 async/await。为了更好地理解如何使用它们并将链转换为异步/等待。此文档包含分步指南:https://advancedweb.hu/how-to-refactor-a-promise-chain-to-async-functions/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2020-02-05
    • 2019-04-07
    • 1970-01-01
    相关资源
    最近更新 更多