我来自Ruby语言,对于noob的问题很抱歉,或者如果我的概念是错误的,请告诉我。
在我的Vue应用程序中,用户应该提供一些数据并异步地获得表单下面的结果。流动就像:
createProductsRequest
)load_id
获得响应,它表示新创建的记录的id,例如12345样例json:{ load_id: 12345 }
load_id
并向Rails后端应用端点发送GET请求(fetchSyncedProductsResultRequest
) (示例json:{result: [{test: 'test'}]}
){result: nil}
),如果是,请重新请求,直到它不为零为止问题是在哪里(以及如何)将步骤5中的循环放在哪里,检查步骤4中给定的响应是否包含null?当响应不是零时,Vue应该停止发送请求。
以下是我迄今所做的工作:
import.js
const createProductsRequest = (self, products) => {
const jwtToken = self.$store.state.idToken;
const payload = JSON.stringify({ product_codes: products['product_codes'].split(',') })
return axios
.post(`/api/v1/imports/products_batches`, payload,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data)
};
const fetchSyncedProductsResultRequest = (token, id) => {
return axios
.get(`/api/v1/imports/products_batches`, {
params: { id: id },
headers: {
Authorization: `Bearer ${token}`,
}
})
.then(response => {
return response.data['result']
})
};
sync_products.vue
<template>
<div class="col-12 col-md-3">
<button
type="button"
class="btn btn-primary"
@click="syncProducts"
>
Sync
</button>
</div>
</template>
<script>
import {
fetchSyncedProductsResultRequest,
createProductsRequest
} from '../../api/imports'
export default {
name: 'SyncProducts',
data() {
return {
fetchedProductSyncStatus: [],
load_id: ''
}
},
async mounted() {
await fetchSyncedProductsResultRequest(this, id)
this.syncedProductsFetched = true
this.pageChanged(this.currentPage)
},
async mounted() {
const jwtToken = this.$store.state.idToken;
fetchSyncedProductsResultRequest(jwtToken).then(data => {
this.fetchedProductSyncStatus = data
})
},
methods: {
async syncProducts() {
let confirmationText = `Do you want to ${this.productsToSyncAmount} sync products?`
if (this.productsToSyncAmount === 0) {
ModalController.showToast('', 'Type product codes for sync first, please!', 'warning')
}
else if (await ModalController.showConfirmation('Confirmation', confirmationText)) {
try {
ModalController.showLoader()
await createProductsRequest(this, this.styleCodes)
const successMessage = `${this.productsToSyncAmount} products have been queued for sync`
await ModalController.showToast('', successMessage)
} catch (data) {
const errorMessage = `Error occurred during queueing products to sync - `
ModalController.showToast('', errorMessage + data?.message, 'error')
} finally {
this.styleCodes = []
ModalController.hideLoader()
}
}
},
}
}
</script>
发布于 2022-05-20 12:39:21
为了节省后端的时间,我可能会等待x段时间(足以让后端创建资源),然后发送get请求-而不是潜在的垃圾邮件。
尽管如此,我认为您希望使用setTimeout函数来调用一个函数,该函数进行API调用。在那里,您可以进行调用,检查结果是否为零,然后使用setTimeout,并在需要时再次调用该函数。就像这样:
async loadId() {
const data = await makeApiRequest()
if (!data.result) {
setTimeout(this.loadId, waitTimeInMillis);
return;
}
//Do what you want if when result isn't null.
}
https://stackoverflow.com/questions/72318433
复制相似问题