为什么 React-query 需要异步 api 调用?

amb*_*960 2 async-await reactjs react-query

每篇文档都显示了与react-query一起使用的异步调用,但我有点困惑为什么这些是必要的,因为以下代码可以使用或不使用async/await

export const apiCall = (method, path, data) => {
    return axios({method, url: API_PREFIX + path, data})
        .then(resp => resp.data)
        .catch(error => {

        });
};

export const useData = () => {
    const {data, isLoading, error, refetch} = useQuery(
        'users',
        async () => await apiCall(dispatch, 'get', '/some-endpoint'),
    );

    return {
        userList: data,
        refetch,
        isLoading
    }
}
Run Code Online (Sandbox Code Playgroud)

TkD*_*odo 13

React-query 希望你返回一个已解决或被拒绝的 Promise - 你可以按照你想要的方式生成它。JavaScript 有很多选项来生成 Promise。.thenasync/await 基本上只是 Promise 与and链接的替代语法.catch

您发布的代码也可以工作,但是,它也有一些不必要的位:

async () => await apiCall(dispatch, 'get', '/some-endpoint'),

你在这里不需要 async / wait ,因为apiCall已经返回了一个 Promise ,所以这将是相同的:

() => apiCall(dispatch, 'get', '/some-endpoint'),

另外,我不会.catch进入该apiCall函数,因为它会将失败的 Promise 转换为成功的 Promise。使用react-query,您确实希望将失败的Promise返回到react-query,以便库可以为您进行错误处理。否则,它不知道错误并且无法重试/无法为您提供错误状态等。

因此对于apiCall,这两件事也将是等效的并且可以很好地与react-query配合使用:

export const apiCall = (method, path, data) => {
    return axios({method, url: API_PREFIX + path, data})
        .then(resp => resp.data)
};
Run Code Online (Sandbox Code Playgroud)
export const apiCall = async (method, path, data) => {
    const response = await axios({method, url: API_PREFIX + path, data})
    return respons.data
};
Run Code Online (Sandbox Code Playgroud)

这实际上只取决于您更喜欢哪种语法 - 大多数人更喜欢 async/await 因为它避免了过多的回调链。

我还写了一篇关于该主题的比较全面的博客文章:https://tkdodo.eu/blog/about-async-functions