【问题标题】:What's better approach for Redux Action Creator: .then or async/await syntax?Redux Action Creator 有什么更好的方法:.then 或 async/await 语法?
【发布时间】:2019-04-25 19:24:00
【问题描述】:

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

推荐什么代码?

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
    })
  )
}

【问题讨论】:

    标签: redux axios redux-thunk


    【解决方案1】:

    它们本质上是相同的。唯一归结为纯粹的偏好。我个人更喜欢 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 语法。您可以尝试/捕获整个代码块,然后也分派错误。在后一种情况下(不使用 async/await),您需要将 .then() 链接到 2 个单独的错误处理程序中。

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 2021-11-05
      • 2019-12-01
      • 2017-04-28
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2020-02-05
      • 2018-02-06
      相关资源
      最近更新 更多