最近項目業務上有個需求,用戶能夠批量下訂單,但每一個訂單都有一個保價費,手續費須要根據訂單的價值由後臺的模型算出來,而後下單的時候每一個訂單都須要帶上這個保價費,因此其實在批量下單前,每一個訂單都須要執行一次後臺接口,不要問我爲何不將訂單都傳給後臺,讓後臺去算,如今的 業務方案是要前端每個訂單都請求一次接口去算出來,而後再批量去下單。
那就寫吧,其實就是調用批量下單的接口前,要先每一個頂你單調一次查保價費的接口,想着很簡單,將保存多選數據的數組遍歷,每次執行一次查保價費的接口就好,而後在遍歷完後再調用下單接口
代碼就這樣寫吧
`const $this = this前端
// 選中多個訂單,更新保價費 // multipleSelection 批量訂單的選中數組 this.multipleSelection.forEach(async(item, index) => { console.log('第' + index + '個訂單開始查詢') //將查到的保價費,賦值到insuredValue getComputationCost爲查保價費接口 $this.multipleSelection[index].insuredValue = await getComputationCost({ value: item.declaredValue, goodsTypeCode: item.goodsTypeCode, }) || 100 console.log('第' + index + '個訂單查詢完成') }) console.log('111', '開始下單') const param = { orders: this.multipleSelection, } //批量下單 const res = await batchAdd(param) console.log('222', '下單完成') if (res.code === RESPONSE_SUCCESS) { this.$message({ message: '下單成功', type: 'success', }) } else { this.$message.error(res.msg) }`
執行一下,報錯了,提示下單接口報錯,保價費不能爲空,奇怪數組
看一下打印
查詢完保價費以前已經調了下單接口,爲何會這樣!
查了一下 async函數會返回一個Promise對象,當函數執行的時候,一旦遇到await關鍵字就會先返回,其實就是跳出async函數體,等到觸發的異步操做完成,再接着執行函數體內後面的語句,而這個async函數返回一個值時,Promise的resolve方法會負責傳遞這個值;當async函數拋出異常的時候,Promise的reject方法會傳遞這個異常值promise
意思是
`異步
$this.multipleSelection[index].insuredValue = await getComputationCost({ value: item.declaredValue, goodsTypeCode: item.goodsTypeCode, }) || 100`
await後面的函數不行行,直接執行後面的async
因此
`函數
const param = { orders: this.multipleSelection, } const res = await batchAdd(param)`
中傳遞到 batchAdd函數的param中的multipleSelection的insuredValue是沒有值的
也就爲何會提示保價費不能爲空this
那若是我須要在forEach中的await執行完以後再執行後面的 await那要怎麼作呢
來點知識普及:await 返回Promise對象的處理結果,實際就是Promise的回調函數resolve的參數;若是等待的不是Promise對象,則返回值自己
咱們都知道Promise是一個當即執行函數,可是他的成功(或失敗:reject)的回調函數resolve倒是一個異步執行的回調。當執行到resolve()時,這個任務會被放入到回調隊列中,等待調用棧有空閒時事件循環再來取走它。
foreach的參數僅僅一個參數回調而foreach自己並非一個 AsyncFunction 全部foreach循環自己並不能實現await效果。spa
我將代碼這樣修改
`// 單個訂單查詢保價費3d
asyncFn (item, index) { return new Promise(async(resolve, reject) => { // console.log('000', '查詢保費') const res = await getComputationCost({ value: item.declaredValue, goodsTypeCode: item.goodsTypeCode, }) console.log(res, index) resolve({ res: res, index: index, }) }) }, async setOrder() { if (this.multipleSelection.length === 0) { return this.$message.error('請先選擇要下單的訂單') } const array = [] const $this = this // 選中多個訂單,更新保價費 this.multipleSelection.forEach((item, index) => { array.push(this.asyncFn(item, index).then(res => { // console.log(index, res) $this.multipleSelection[index].insuredValue = res.data || 100 })) }) Promise.all(array).then(async(result) => { // console.log('all', result) // console.log('666', '開始下單') const param = { orders: this.multipleSelection, } const res = await batchAdd(param) // console.log('下單完成', res) if (res.code === RESPONSE_SUCCESS) { this.$message({ message: '下單成功', type: 'success', }) } else { this.$message.error(res.msg) } }) },`
執行一下,提示下單成功
看一下打印code
是我想要的效果了
原理就是經過一個promise函數,將每一次請求保價費的請求放到一個數組裏,經過promise.all,去處理,而後在這個promise對面的resolve裏面去執行批量下單的操做。