首页 > 解决方案 > 如何使用 aync 和 await 调用函数的内部使用效果?

问题描述

我正在调用以下函数,如下所示。如何将异步等待提供给 serviceRequest 和成功处理程序

useEffect(() => {
    serviceRequest(
      "URL",
      success,
      error
    );
  }, []);
  
   const success = (response) => { }
   const error = (error) => { }

export const serviceRequest = (endpoint,successCallBack,errorCallBack) => {
    const options: any = {
        withCredentials: true,
        headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        }
      }
    axios.get(endpoint, options)
        .then((response) => {
            successCallBack(response.data)
        }) 
        .catch(error => {errorCallBack(error) })
}

标签: reactjs

解决方案


好吧,首先确保 serviceRequest 函数返回一个承诺。在这种情况下,您可以简单地返回 axios 结果:

export const serviceRequest = (endpoint,successCallBack,errorCallBack) => {
const options: any = {
    withCredentials: true,
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    }
  }

  return axios.get(endpoint, options)
}

然后你可以在你的使用效果处理程序中使用承诺,在 useState 钩子中捕获结果/错误,如下所示:

const [result, setResult] = useState(null);
const [error, setError] = useState(null);

useEffect(() => {
  serviceRequest("URL")
    .then((result) => setState(result)
    .catch(error => setState(error)
  };
}, []);

推荐阅读