async wait not working in composable function vue 3
P粉752826008
P粉752826008 2024-03-25 20:48:21
0
2
542

In my project, I have a function to download files. When the button is clicked, function onDownload will be called:

import {useOnDownload} from "../../use/useOnDownload"

setup() {

    ...

    const loading = ref(null)
    onDownload = (id) => {
        loading.value = id
        await useOnDownload(id)
        loading.value = null
    }
    
    return {loading, onDownload}
}

I refactored the api code in the useOnDownload.js calling file because other components also use the same code.

export async function useOnDownload(id) {
    // make api call to server with axios
}

What did i do wrong? I need to wait for the function useOnDownload ... for the loader to work properly.

P粉752826008
P粉752826008

reply all(2)
P粉071559609

The following is how to use async wait syntax to create an asynchronous composable function

export default function useOnDownload() {
  const isLoading = ref(true);

  const onDownload = async () => {
    isLoading.value = true;
    try {
      const { data } = await axios.post('/api/download', {id: id}, 
     {responseType: 'blob'})
        // handle the response

    } catch (error) {
      console.log(error);
    } finally {
      isLoading.value = false;
    }
  };
   // invoke the function
  onDownload();

  return { // return your reactive data here };
}


import useOnDownload from "../../use/useOnDownload"
// no await in setup script or function 
const { reactiveDataReturned } = useOnDownload();

Clickherefor more information

P粉764003519

I managed to solve another way without async and await...

I pass the reference object loader to the function argument (as optional) and handle it from there...

export function useOnDownload(id, loader) {
   if(loader !== undefined) {
     loader.value = id
   }
   axios.post('/api/download', {id: id}, {
      responseType: 'blob'
   }).then(response => {
     // handle the response
     ...
     if(loader !== undefined) {
       loader.value = null
     }
   }).catch(error => {
     // handle the error
     ...
     if(loader !== undefined) {
       loader.value = null
     }
   })
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template