【问题标题】:How to use debounce on async function? [duplicate]如何在异步功能上使用 debounce? [复制]
【发布时间】:2018-11-23 00:56:32
【问题描述】:

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

这是我的方法:

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 debouncing debounce


    【解决方案1】:

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

    所以这样做:

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

    【讨论】:

    • 非常感谢!然而如此简单:-)
    • 与 await 一起使用时似乎无法正确返回值
    • 仅当 lodash debounceleading 选项设置为 true 时才有效。
    • @user1843640 很抱歉劫持了一条旧评论,但它是否有理由只与leading : true 一起使用?对我来说,这会导致不需要的行为,例如如果用户在搜索字段中键入“搜索”,那么它只会在“s”上进行搜索
    猜你喜欢
    • 2019-09-04
    • 2021-12-11
    • 2018-01-15
    • 2020-01-11
    • 2016-11-27
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    相关资源
    最近更新 更多