stop promises to modify state


This Content is from Stack Overflow. Question asked by stefan

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(() => {
  }, 5000)

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

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?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?