[英]Vue: Best practices for handling multiple API calls
因此,我發現自己在vuex動作中進行了多個API調用,這讓我想知道什么是處理這種情況的最佳方法,多個API調用的最佳實踐,讓我們從我擁有的代碼開始。
我有一個動作,我收集了來自不同API端點(后端為laravel)的所有帖子和所有帖子類別,我敢肯定有比我做的更好的方法:
fetchAllPosts ({ commit }) { commit( 'SET_LOAD_STATUS', 1); axios.get('/posts') .then((response) => { commit('FETCH_ALL_POSTS', response.data.posts ) commit( 'SET_LOAD_STATUS', 2 ); }, (error) => { console.log(error); commit( 'SET_LOAD_STATUS', 3 ); }) axios.get('/postcategories') .then((response) => { commit('FETCH_ALL_POSTCATEGORIES', response.data.postcategories ) commit( 'SET_LOAD_STATUS', 2 ); }, (error) => { console.log(error); commit( 'SET_LOAD_STATUS', 3 ); }) },
我想到的方法的第一個問題是,如果第一個API調用失敗,但是第二個API調用成功,那么我將獲得2的加載狀態(此處2等於成功)!
如果第一個和第二個API調用都正確地獲取了數據,我只想處理提交,請幫助正在學習的人。
我想您可能想讀一下諾言 。
在您的示例中,您使用的是Axios,它是一個基於Promise的HTTP客戶端,它很棒。
使用Promises,您可以執行多個請求,當所有請求成功后,您便可以執行代碼。
使用Axios,您可以使用.all來做到這一點,如下所示:
axios.all([getPosts(), getPostCategories()])
.then(axios.spread(function (posts, categories) {
// Both requests are now complete
}));
axios.all([
axios.get(firstUrl),
axios.get(secondUrl)
])
.then(axios.spread(function (response1, response2) {
//response1 is the result of first call
//response2 is the result of second call
}))
.catch(function (error) {
});
有關catch()的注意事項:在第一個失敗的請求上將調用它,而忽略其余的調用。 因此,如果第一個調用失敗,則即使沒有發出第二個請求也將調用catch()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.