0

In my app I want to show files for different Items. When item A is selected, it can take some time until it is loaded. When in the meantime item B is selected, how can I stop the loading of item A?

Take this simplified example of my use case:

<script setup>
import { reactive } from 'vue'
const files = reactive([])

function load(item) {
  // reset files
  files.length = 0
  // simulate long running process with setTimeout
  setTimeout(() => {
    files.push(item)
  }, 5000)
}
</script>

<template>
  <button @click="load('A')">A</button>
  <button @click="load('B')">B</button>
  <pre>files: {{ files }}</pre>
</template>

When clicking the buttons A and B within less than 5seconds, the files list will show A and B eventually, but I want it to only show B.

My real use case is more complex and involves multiple state variables (not only files) and multiple Promises spawned in the background to populate these variables.

Any ideas on how this can be achieved?

stefan
  • 188
  • 1
  • 7
  • 1
    hey mate, did you try with [Promise.race()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) or [Promise.any()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any) – Nikola Pavicevic Sep 18 '22 at 19:56
  • The accepted answer [here](https://stackoverflow.com/questions/30233302/promise-is-it-possible-to-force-cancel-a-promise) has a lot of good info. – Yitz Sep 18 '22 at 21:59
  • Although a simple solution (if you don't care about cancelling those api calls) would be to set a variable `lastCalled` in your data to some random data (a uuid maybe?) and then before populating `files`, check whether `lastCalled` is still set to what you set it as. – Yitz Sep 18 '22 at 22:03

0 Answers0