如何在异步函数上使用去抖动? [英] How to use debounce on async function?

查看:33
本文介绍了如何在异步函数上使用去抖动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 async 函数上使用 debounce?我在我的 vue-app 中有一个方法,它从一个 API 中获取数据,该 API 不断调用我想避免的 API.

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.

这是我的方法:

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

我之前已经安装了 lodash 那么我该如何实现呢?

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

推荐答案

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

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

所以这样做:

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

这篇关于如何在异步函数上使用去抖动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆