Redux Action Creator 的更好方法是什么:.then 或 async/await 语法?

What's better approach for Redux Action Creator: .then or async/await syntax?

例如比较下面的两个代码,第一个使用 async/await 另一个调用 axios .then.

推荐什么代码?

const BASE_URL = "https://jsonplaceholder.typicode.com"

// async await syntax
export const fetchPosts = () => async dispatch => {
  const response = await axios.get(BASE_URL + "/posts")
  dispatch({ type: "FETCH_POSTS", payload: response })
}

// using .then instead
export const fetchPosts2 = () => dispatch => {
  axios.get(BASE_URL + "/posts").then(response =>
    dispatch({
      type: "FETCH_POSTS",
      payload: response
    })
  )
}

它们本质上是相同的。唯一归结为纯粹的偏好。我个人更喜欢 async/await 语法,因为它可以让你在进行多次调用时避免一些潜在的麻烦,避免一些特别讨厌的嵌套调用:

// async await syntax
export const fetchPosts = () => async dispatch => {
  const posts = await axios.get(BASE_URL + "/posts")
  const users = await axios.get(BASE_URL + "/users", {
    params: posts.map(p => p.author_id)
  })
  dispatch({ type: "FETCH_POSTS", payload: {
      posts, users
  }})
}

对比:

// async await syntax
export const fetchPosts = () => dispatch => {
  axios.get(BASE_URL + "/posts").then(posts =>
    axios.get(BASE_URL + "/users", {
      params: posts.map(p => p.author_id)
    }).then(users => {
      dispatch({ type: "FETCH_POSTS", payload: {
          posts, users
      }})
    })
  )
}

也不要忘记 try/catch 语法。您可以 try/catch 整个代码块,然后也发送错误。在后一种情况下(不使用 async/await),您需要将 .then() 链接到 2 个单独的错误处理程序中。