如何在异步函数上使用去抖动?

时间:2018-06-13 12:27:55

标签: javascript vue.js vuejs2 debouncing debounce

如何在debounce功能上使用async?我在vue - 应用程序中有一个方法,可以从API中继续调用API,这是我想要避免的。

这是我的方法:

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

我以前安装了lodash,我该如何实现?

2 个答案:

答案 0 :(得分:3)

Lodash的debounce函数接受一个函数,等待的时间并返回一个函数。

所以这样做:

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

答案 1 :(得分:0)

如果您只想要去抖一段时间,虽然该函数是异步的,但lodashs方法仍然有效。如果你想要去抖动,直到异步调用成功,你可能需要一个自定义的去抖动器:

function debounceAsync(fn) {
  let block = false;
  return async function(...args) {
   if(block) return;
   block = true;
   await fn(...args);
   block = false;
  }
}