How to use debounce on async function?

23,546

Lodash's debounce function takes in a function , time to wait and returns a function.

So do it like this:

methods: {
  getAlbums: _.debounce(async function() {
    const response = await AlbumService.fetchAlbums();
    this.albums = response.data.albums;
  }, 1000);
}
Share:
23,546
ST80
Author by

ST80

Updated on June 14, 2020

Comments

  • ST80
    ST80 almost 4 years

    How can I use debounce on an async function? I have a method within my vue-app which reveives data from an API which calls the API continuosly which I want to avoid.

    Here is my method:

    methods: {
        async getAlbums () {
         const response = await AlbumService.fetchAlbums()
         this.albums = response.data.albums
        } 
    }
    

    I've installed lodash previously so how can I achieve that?

  • ST80
    ST80 almost 6 years
    Thanks alot! Yet so simple though :-)
  • Zia Ul Rehman Mughal
    Zia Ul Rehman Mughal over 4 years
    Doesn't seem to be returning values properly when used with await
  • user1843640
    user1843640 over 4 years
    Only works when the lodash debounce leading option is set to true.
  • Chris A
    Chris A almost 4 years
    @user1843640 Sorry to hijack an old comment but is there a reason for it only working with leading : true? For me this causes unwanted behaviour, like if the user types 'search' in a search field then it will do the search only on 's'