sweetalert not waiting in async methods with vue3

55 Views Asked by At

I am trying to use SweetAlert2 with Vue3 (composition API). With the following code, the alert doesn't wait for its button to be clicked:

onBeforeMount(async() => {
  Swal.fire('test message');
  initialiseArrays();
  await getRides();
});

If I remove async,

onBeforeMount(() => {
  Swal.fire('test message');
  initialiseArrays();
  //await getRides();
});

or add async to the 'Swal' call, it works as expected:

onBeforeMount(async() => {
  async Swal.fire('test message');
  initialiseArrays();
  await getRides();
});

The function getRides waits for data from the server and populates some lists. I don't actually need to use Swal in onBeforeMount(), but it will be used deeper inside getRides, where again it does not work unless I add await to every use of Swal. But that means making virtually every function of my code async - which cannot be right!

I have tried moving part of the getRides code into the onMounted hook, but that is called before the data is fully loaded, so leads to complications. I will however progress with this method unless there is no other solution.

1

There are 1 best solutions below

0
quilkin On

I wasn't aware (or had forgotten) that Swal is non-blocking, so just calling a second will immediatly destroy the first, unless either

  • each call has await, which then means that any function using it must be declared async, (see here for a complete answer) or
  • call the subsequent alert in a callback of the first - see here for lots more details - this will require some code restructuring on my part, since there are multiple uses deep in my getRides function.