例如比较下面的两个代码,第一个使用 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
})
)
}
它们本质上是相同的。它唯一归结为纯粹的偏好。我个人更喜欢 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()
's 链接到 2 个单独的错误处理程序中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句