Home  >  Q&A  >  body text

async wait not working in composable function vue 3

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粉752826008P粉752826008207 days ago469

reply all(2)I'll reply

  • P粉071559609

    P粉0715596092024-03-26 15:31:51

    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

    reply
    0
  • P粉764003519

    P粉7640035192024-03-26 09:19:39

    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
         }
       })
    }

    reply
    0
  • Cancelreply