首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue发送请求,直到从另一个请求得到结果

Vue发送请求,直到从另一个请求得到结果
EN

Stack Overflow用户
提问于 2022-05-20 11:46:57
回答 1查看 74关注 0票数 0

我来自Ruby语言,对于noob的问题很抱歉,或者如果我的概念是错误的,请告诉我。

在我的Vue应用程序中,用户应该提供一些数据并异步地获得表单下面的结果。流动就像:

  1. 用户提供输入数据
  2. 应用程序向Rails后端应用程序发送POST请求(createProductsRequest)
  3. 使用load_id获得响应,它表示新创建的记录的id,例如12345样例json:{ load_id: 12345 }
  4. Vue应用程序使用load_id并向Rails后端应用端点发送GET请求(fetchSyncedProductsResultRequest) (示例json:{result: [{test: 'test'}]})
  5. 检查response.result是否为零({result: nil}),如果是,请重新请求,直到它不为零为止
  6. 显示响应数据

问题是在哪里(以及如何)将步骤5中的循环放在哪里,检查步骤4中给定的响应是否包含null?当响应不是零时,Vue应该停止发送请求。

以下是我迄今所做的工作:

import.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2022-05-20 12:39:21

为了节省后端的时间,我可能会等待x段时间(足以让后端创建资源),然后发送get请求-而不是潜在的垃圾邮件。

尽管如此,我认为您希望使用setTimeout函数来调用一个函数,该函数进行API调用。在那里,您可以进行调用,检查结果是否为零,然后使用setTimeout,并在需要时再次调用该函数。就像这样:

代码语言:javascript
运行
复制
async loadId() {
  const data = await makeApiRequest()
  if (!data.result) {
    setTimeout(this.loadId, waitTimeInMillis);
    return;
  }
  //Do what you want if when result isn't null.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72318433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档