异步功能

时间:2019-09-26 02:24:35

标签: javascript reactjs async-await

我有一个功能

export const setSearchField = text => dispatch => {
  dispatch({ type: REQUEST_GIFS_PENDING });
  fetch(API_URL + (text || DEFAULT_QUERY) + API_KEY + LIMIT)
    .then(response => response.json())
    .then(items =>
      dispatch({ type: REQUEST_GIFS_SUCCESS, payload: items.data })
    )
    .catch(error => dispatch({ type: REQUEST_GIFS_FAILED, payload: error }));
};

现在,我想将其转换为异步函数,我确实做到了这一点,而没有try&catch,但是它不起作用

export const setSearchField = text => dispatch => {
  dispatch({ type: REQUEST_GIFS_PENDING });
  async function fetUsers(){
    const response = await fetch(API_URL + (text || DEFAULT_QUERY) + API_KEY + LIMIT);
    const items = await response.json();
    dispatch({ type: REQUEST_GIFS_SUCCESS, payload: items.data })
  }

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您的代码无法正常工作的原因是,您永远不会调用已创建的异步函数。但是,没有任何理由要创建内部异步函数;只需使您已经异步的一个即可:

export const setSearchField = text => async (dispatch) => {
  dispatch({ type: REQUEST_GIFS_PENDING });
  try {
    const response = await fetch(API_URL + (text || DEFAULT_QUERY) + API_KEY + LIMIT);
    const items = await response.json();
    dispatch({ type: REQUEST_GIFS_SUCCESS, payload: items.data })
  } catch (error) {
    dispatch({ type: REQUEST_GIFS_FAILED, payload: error })
  }
}