【问题标题】:use try catch blocks for graphql queries对 graphql 查询使用 try catch 块
【发布时间】:2020-09-18 02:56:31
【问题描述】:

以前,我在我的 graphql 查询处理中使用 .then 回调。

以前的代码:

  let submitForm = (freeSeats: Number, numberPlate: string, userId: Number) => {
    setIsSubmitted(true);
    addVehicle({
      variables: {
        freeSeats: freeSeats,
        numberPlate: numberPlate,
        userId: userId,
      },
    })
      .then(({ data }: ExecutionResult<CreateVehicleResponse>) => {
        if (data !== null && data !== undefined) {
          setIsAdded(true);
        }
      })
      .catch((error: { message: string }) => {
        setIsAdded(false);
        setErrorMessage(error.message);
      });
  };

我现在正试图切换到 try catch 块,但我无法这样做。我试图更改为异步函数,但如果我删除 .then 行,我会收到数据错误,因为找不到它。在这种情况下,使用 try catch 块的正确方法是什么?

【问题讨论】:

  • addVehicle 是一个 Promise,你无法知道它是否成功使用 try catch,而是必须使用和 catch (这是设计使然)developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 您应该解释为什么要使用 try catch,也许人们会为您的意图建议更好的解决方法
  • Wdym by 你不知道它是否成功?如果没有,我会得到一个错误,可以被 catch 捕获,不是吗?听说我的高级开发人员说我们应该删除 .then 回调并使用异步等待。不知道为什么(还)。 @volna
  • 许多人认为只有在等待响应返回时不希望执行任何业务逻辑代码时才应使用异步等待。在所有其他情况下,promise 仍然是更好的设计选择。我建议您阅读:hackernoon.com/…
  • 然后尝试了解您的业务逻辑需要什么,然后选择真正合适的方法。我个人觉得陷入了多次异步等待的陷阱,其中可以使用一个简单的 Promise。

标签: javascript reactjs typescript graphql try-catch


【解决方案1】:

为了将.then转换为async-await,你需要在函数上指定async关键字,然后在promise之前使用await

上面带有 async-await 的代码看起来像

let submitForm = async (freeSeats: Number, numberPlate: string, userId: Number) => {
  try {
    setIsSubmitted(true);
    const {data} = await addVehicle({
      variables: {
        freeSeats: freeSeats,
        numberPlate: numberPlate,
        userId: userId,
      },
    })
    if (data !== null && data !== undefined) {
          setIsAdded(true);
    }
   } catch(error: { message: string }) {
        setIsAdded(false);
        setErrorMessage(error.message);
   };
  }; 

【讨论】:

  • 不错的解决方法,但是您会批准某人的 PR 使用这种方法吗? :-)
  • @volna 我为什么不这样做。你认为它有什么问题?为什么你认为它是一种解决方法?
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2011-07-09
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
相关资源
最近更新 更多