【问题标题】:How to get return error value of function? (React Native)如何获取函数的返回错误值? (反应原生)
【发布时间】:2019-07-08 12:05:34
【问题描述】:

我在新函数中创建 async/await(try...catch)。

我在另一个组件中调用这个函数。 然后,我只想得到返回错误值并显示错误值。

我该怎么做?

我的功能:

const updateInformation = async () => {

try {
  const response = await updateAPI({
    variables: {
      data: {
        name: state.name,
        phoneNumber: state.phoneNumber,
      },
    },
  })
} catch (ex) {
  return Utils.extractErrorMessage(ex)
}
}

组件:

const onPressSendButton = () => {
if (name && address1 && address2 && phoneNum) {
  const r = updateInformation()
  // I want to show return error value in this line.
} else {
  return false
}
}

【问题讨论】:

  • 什么是updateAPI 表示您正在使用fetch 或其他什么?
  • @ravibagul91 updateAPI 是突变(阿波罗)。
  • 不知何故,你没有像我猜的那样使用这个异步函数。因为异步函数总是返回一个promise。因此,无论是在普通块中还是在 error 块中,如果您返回某些东西,您就会将其作为承诺解决。那么,如果只解决错误是您的真正意图,您在哪里检查 updateAPI 是否在您的代码中引发错误?

标签: javascript reactjs react-native


【解决方案1】:

我做了一些更改,这应该可以工作(附有解释):

功能

const updateInformation = async () => {
    return updateAPI({ // Missing return
        variables: {
            data: {
                name: state.name,
                phoneNumber: state.phoneNumber,
            },
        },
    });
};

组件

const onPressSendButton = async () => {
    if (name && address1 && address2 && phoneNum) {
        try {
            const r = await updateInformation(); // Need to await here
        } catch (e) {
            // This is where you handle the error
        }
    } else {
      return false;
    }
};

【讨论】:

  • onPressSendButton 必须是异步函数,如果您使用的是await
  • 是的,很好看@devserkan
  • 你是对的@ravibagul91,在这种情况下实际上没用
  • 感谢您的解决方案!但是,onPressSendButton不能通过从updateInformation返回错误得到updateInformation的解析结果吗?
  • 如果你从你的函数返回错误,那么你可以得到@Nevroz在这里建议的结果。
猜你喜欢
  • 2017-10-21
  • 1970-01-01
  • 2017-12-23
  • 2015-12-31
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2014-05-04
  • 2021-02-13
相关资源
最近更新 更多