What benefits do “async actions” of redux bring?

Redux documentation says that to do async calls—which would typically involve an action indicating the start of the async call, and a later action indicating its completion—I should use the “thunk” middleware. This allows me to write “actions creators” like this:

function fetchPosts(reddit) {
  return dispatch => {
    dispatch(requestPosts(reddit))
    return fetch(`http://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => dispatch(receivePosts(reddit, json)))
  }
}

(Here requestPosts and receivePosts are action creators.)

The thunk middleware allow me to dispatch the (function) output of fetchPosts, e.g.,

store.dispatch(fetchPosts('reactjs')).then(() =>
  ...

But why involve middleware at all? Why is this better than just writing my own fetchPost function using the global store, like this:

function fetchPosts(reddit) {
  store.dispatch(requestPosts(reddit));
  return fetch(`http://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => store.dispatch(receivePosts(reddit, json)))
  }
}

Obviously, I can’t dispatch this function, but that doesn’t seem terribly important. What am I missing?

发表评论

电子邮件地址不会被公开。 必填项已用*标注