简体   繁体   English

如何获得函数的返回错误值? (反应本机)

[英]How to get return error value of function? (React Native)

I create async/await(try...catch) in new function. 我在新函数中创建async / await(try ... catch)。

and I call this function in another component. 我在另一个组件中调用此函数。 then, I want to get only return error value and show error value. 然后,我只想返回错误值并显示错误值。

How do I do it? 我该怎么做?

My Function: 我的职能:

const updateInformation = async () => {

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

Component: 零件:

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

I made some changes, this should work (commented with explanations) : 我进行了一些更改,这应该可以工作(并附有说明):

Function 功能

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

Component 零件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM