我有兩個表單,其中包含需要使用兩個單獨的 post API 保存的資料。我正在使用 Promise.all() 一次保存這兩個表單中的所有資料,并且它應該正常作業。代碼如下:
saveAll() {
Promise.all([
this.$axios.post('v1/dummy-api/one',
this.saveFormOne()
),
this.$axios.post('v1/dummy-api/two',
this.saveFormTwo()
)
])
.then(() => {
this.success = 'Added Successfully.';
})
.catch(error => {
this.error = 'Error.';
})
},
我要解決的問題是我需要檢查這兩個請求中的任何一個是否失敗,如果確實如此,則阻止/取消另一個(成功)的保存,直到所有請求都成功。我試過嘗試/捕捉但沒有運氣。
任何幫助將不勝感激!
uj5u.com熱心網友回復:
您需要使用 Axios AbortController ( https://axios-http.com/docs/cancellation )。請注意,取消請求可能不一定保證 POST 尚未正確執行。如果您在一個失敗的情況下不能呼叫另一個端點,最簡單的方法是鏈接它們并一個接一個地呼叫。
無論如何,下面顯示了實作此目的的方法。請注意,我需要對其進行一些修改,以便它可以在 stackoverflow 答案中執行。不過,你會從中得到一個大致的想法。
function saveAll() {
const cancel = new AbortController();
Promise.all([
axios.get('https://test-stackoverflow.free.beeceptor.com', {}, {
signal: cancel.signal
}).catch((e) => {
cancel.abort();
throw e;
}),
axios.get('https://thiswillfail.com/fail', {}, {
signal: cancel.signal
}).catch((e) => {
console.log('second request has failed')
cancel.abort();
throw e;
})
])
.then(() => {
alert('Added Successfully.');
})
.catch(error => {
alert('Error.');
})
}
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<button onclick="saveAll()">save all</button>
uj5u.com熱心網友回復:
async saveAll() {
const resp1 = await this.$axios.post('v1/dummy-api/one', this.saveFormOne())
const resp2 = await this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
}
不知道這個能不能解決
uj5u.com熱心網友回復:
Promise.all()如果您需要管理這些 API 呼叫,這不是您所需要的。你可以做一些類似于王超華建議的事情,但需要額外的try/catch
async function saveAll() {
let first;
try {
first = await this.$axios.post('v1/dummy-api/one', this.saveFormOne())
} catch (e) {
console.log('first failed')
return
}
console.log('first', first)
const second = await this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
console.log('second', second)
}
或者如果你想使用 Promises
saveAll() {
this.$axios.post('v1/dummy-api/one', this.saveFormOne())
.then(() => this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
.then(() => this.success = 'Added Successfully.')
.catch(error => this.error = 'Error.')
}
uj5u.com熱心網友回復:
我不確定您如何發送請求,但同時取消它。
一個請求可能會在幾個點失敗,如果在資料庫嘗試保存物體時你的事情失敗了,你不能真正從客戶端取消它(不發送另一個 HTTP 呼叫)。
從您的客戶端發送另一個 HTTP 呼叫以更新后端的失敗狀態,或者讓后端回滾您嘗試過的內容(如果它不正確)。
這個問題是詢問如何解決有關此處系統設計的問題。解決方案不在前端,而是在后端/實作本身。
你需要想辦法:
- 在不同后端完成的操作之間的通信(以某種方式通過中間件后端或類似方式鏈接它們)
- 在發送 2 個 HTTP 呼叫之前對客戶端進行驗證(通過模擬或客戶端驗證)
- 實施一些回滾
最干凈的方法是使用Promise.allSettled,并帶有關于兩個端點(如果可用)的類似dry-runala的引數git,這樣您就可以模擬兩者的執行和結果(并防止任何網路錯誤),然后重新運行如果模擬正確,則兩側的查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478073.html
標籤:javascript Vue.js 承诺 nuxt.js 承诺.all
下一篇:在VueSFC中獲取回圈鍵
