[英]Execute method after all promises inside of a given method resolved
在Vue.js組件中,我有一些使用axios調用API的方法。
在不同情況下,一旦此方法中的調用已解決,我就需要執行一些代碼,但是我不想在.then .then()
添加一堆if
語句,這些語句鏈接到axios調用。
methods: {
callApi() {
axios.get('/api')
.then(() => {
// call has resolved, request is done
})
},
firstMethod() {
this.callApi()
// Need to wait for the call to resolve
// Do something
},
secondMethod() {
this.callApi()
// Need to wait for the call to resolve
// Do something else
}
}
如您所見, firstMethod
和secondMethod
都依賴於callApi
但是一旦請求完成,它們應該做不同的事情。 我更喜歡將此邏輯拆分為不同的函數,而不是在callApi
方法中使用條件。 有沒有一種方法可以不必在callApi
內部添加此邏輯?
讓callApi
返回承諾鏈,然后在firstMethod
和secondMethod
使用並返回它。
methods: {
callApi() {
return axios.get('/api')
.then(() => {
// call has resolved, request is done
})
},
firstMethod() {
return this.callApi()
.then(() => {
// Need to wait for the call to resolve
// Do something
})
},
secondMethod() {
return this.callApi()
.then(() => {
// Need to wait for the call to resolve
// Do something else
})
}
}
任何調用callApi
, firstMethod
或secondMethod
都應檢查故障並處理/報告故障。
您的原始代碼違反了promise的規則之一:函數應始終返回鏈或處理拒絕。 (是的,這是或 [的99.9%的時間],不和 。)
承諾鏈,因此您需要保證Axios返回,執行您可能需要執行的所有處理,然后從callApi
方法返回它。 在調用callApi
其他方法中,您將處理返回的callApi
,並將在API響應后必須運行的所有代碼放入處理程序函數中。
callApi() {
return axios.get('/api')
.then(() => {
// this gets handled first
})
},
firstMethod() {
this.callApi()
.then(() => {
// this gets handled second
})
},
secondMethod() {
this.callApi()
.then(() => {
// or this gets handled second
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.