例如,比较下面两个代码,第一个使用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
})
)
}
答案 0 :(得分: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
}})
}
vs:
// 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语法。您可以尝试/捕获整个代码块,然后也分派错误。在后一种情况下(不使用异步/等待),您需要将.then()
链接到2个单独的错误处理程序中。