10

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
  • 3,565
  • 16
  • 64
  • 124

1 Answers1

25

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);
}
Vamsi Krishna
  • 30,568
  • 8
  • 70
  • 78
  • 26
    Doesn't seem to be returning values properly when used with await – Zia Ul Rehman Mughal Nov 22 '19 at 06:25
  • 12
    Only works when the lodash debounce leading option is set to true. – user1843640 Jan 18 '20 at 12:55
  • 9
    @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' – Chris A Jun 13 '20 at 12:41
  • @ZiaUlRehmanMughal, have you found any away to return the value with async. – EaBengaluru Nov 23 '22 at 16:40
  • @ChrisA because `leading: true` call the method immediately so the promise that we are expecting is available. unfortunately the `lodash.debounce` is not working properly with `leading: true`. https://stackoverflow.com/questions/52505376/leading-true-in-debounce-not-performing-as-expected – Saman Mohamadi Apr 05 '23 at 07:05