javascript - 如何获取函数的返回错误值? ( react native )

标签 javascript reactjs react-native

我在新函数中创建 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
}
}

最佳答案

我做了一些更改,这应该有效(带有解释注释):

函数

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;
    }
};

关于javascript - 如何获取函数的返回错误值? ( react native ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56934568/

相关文章:

javascript - 如何在呈现浏览器中的任何内容之前加载大图像

react-native - 将替代调色板设置为 native 库中的默认主题

email - 尝试生成 PDF 并使用 React Native 查看或通过电子邮件发送

css - React 样式组件,动画 : invert the position of two divs

javascript - expo sqlite 使用现有数据库

javascript - 如何在浏览器上使用手机麦克风录音?

javascript - 在 JavaScript 中,当必须缩小文件时省略分号是否安全?

javascript - 如何连续运行 socket.io 服务器?

javascript - 在 Jest 快照中模拟 css 模块

javascript - 如何使用 React Hook useEffect 检查状态默认 bool 值 false 是否更改为 true