Home > Software design >  How can I change setTimeout to send the request until a value is received?
How can I change setTimeout to send the request until a value is received?

Time:05-25

In my app I've got functionality where user can import spreadsheet file. The file itself is sending to backend app and after some time it the result can be fetched from different endpoint based on ID. The thing is it can take a very long time for the backend to prepare a response and this time varies depending on the file size. So far I've been using setTimeout function but since the backend response time is different I can't do it.

Here is my code:

new_batch.vue

export default {
  name: 'BackboneSyncProducts',
  data() {
    return {
      styleCodes: [],
      fetchedProductSyncResult: [],
      loadId: null,
    }
  },
  watch: {
    loadId(newValue, oldValue) {
      if (!oldValue && newValue) {
        setTimeout(() => {
          fetchSyncedProductsResultRequest(this, newValue).then(response => {
            this.fetchedProductSyncResult = response.data['result']
          })
        }, 3000)
      }
    }
  },

Whole functionality needs to be asynchronous. How to hit backend app using fetchSyncedProductsResultRequest function until response.data['result'] is not is null ?

CodePudding user response:

Try sending several requests using setInterval until the file will be processed on backend and will return a non-null value. You can also use websockets but that will require updating backend API.

export default {
  name: 'BackboneSyncProducts',
  data() {
    return {
      styleCodes: [],
      fetchedProductSyncResult: [],
      loadId: null,
    }
  },
  watch: {
    loadId(newValue, oldValue) {
      if (!oldValue && newValue) {
        const intervalId = setInterval(() => {
          fetchSyncedProductsResultRequest(this, newValue).then(response => {
            if (response.data['request']) {
              clearInterval(intervalId);
              this.fetchedProductSyncResult = response.data['result']
            }
          })
        }, 1000)
      }
    }
  },
  • Related