reactjs - 如何使用 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) })
}
解决方案
好吧,首先确保 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)
};
}, []);
推荐阅读
- c# - 尝试通过存储过程插入值
- mysql - 如何使用附加的终端和 dockerfile 在我的容器中构建我的 MySQL 脚本和表
- angular - Angular 覆盖全局 ErrorHandler
- python - Python - 从多个级别获取嵌套数据
- html - 一种让不同列中的多个 div/元素共享相同高度的方法?
- vba - 如何完全删除文件夹的自定义字段/用户定义属性?
- r - 服务器端选择在 R Shiny 应用程序中不起作用
- flutter - 图片资源路径未设置
- sql - SQL Server 事务日志文件出现在错误的位置
- r - 使用来自多个现有图像的魔法在 R 中组合新图形