【发布时间】:2020-06-22 19:33:01
【问题描述】:
我在 React 应用程序中使用基于 Promise 的钩子从 API 获取异步数据。
我也在使用 Axios,一个基于 Promise 的 http 客户端来调用 API。
在另一个 Promise 中使用基于 Promise 的客户端是一种反模式吗?下面的代码似乎不起作用。
const getData = () => {
return new Promise((resolve, reject) => {
const url = "/getData";
axios.get(url)
.then(function(response) {
resolve(response);
})
.catch(function(error) {
reject(error);
});
});
const useAsync = (asyncFunction) => {
const [value, setValue] = useState(null);
const execute = useCallback(() => {
setPending(true);
setValue(null);
setError(null);
return asyncFunction()
.then(response => setValue(response))
.catch(error => setError(error))
.finally(() => setPending(false));
}, [asyncFunction]);
useEffect(() => {
execute();
}, [execute]);
return { execute, pending, value, error };
};
};
const RidesList = () => {
const {
pending,
value,
error,
} = useAsync(getData);
【问题讨论】:
-
您有什么理由不使用
async await吗? -
你遇到了什么错误?
-
我需要查找异步等待。我认为每次调用都使用相同的钩子会使代码可读。我没有收到任何错误,我只看到承诺无限期等待。
标签: reactjs axios react-hooks es6-promise