'async await not working in composable function vue 3

In my project I have a function for downloading the files. When click the button the 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 code for api in a file useOnDownload.js call because the same code is used in another components as well.

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

What I did wrong? I need to wait for the function useOnDownload ... in order the loader to work.



Solution 1:[1]

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

I passed the reference object loader to the function parameter (as optional) and handle 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
     }
   })
}

Solution 2:[2]

onDownload must be async in order to use await within it

Solution 3:[3]

You are using the await keyword in your onDownlaod function, but the function is not asynchronous. Here's how you should update it.

   // next line important
   onDownload = async(id) => {
    loading.value = id
    await useOnDownload(id)
    loading.value = null
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 calin24
Solution 2 Mossaab
Solution 3 Sami Salih ?brahimba?