lodash中flush的使用(debounce、throttle)

时间:2024-07-06 07:50:54

在项目的配置中,看到了一个请求,类似是这样的

import { throttle } from 'lodash-es'

// 请求函数
async function someFetch(){
     const {data} = await xxx.post()
    return data
}

// 节流函数
async function throttleFn(someFetch,1000)


// 执行拿到数据函数
async function getDataFn(enforcement){
    return enforcement? await throttleFn.flush() : await throttleFn()
}

        逻辑很简单,因为有个节流函数1秒执行一次,所以接收了一个 enforcement 作为参数来让节流函数失效,让请求再强制执行一次。

        但你会发现,执行 getDataFn(true),请求函数 someFetch.flush() 并没有去发送请求,而直接执行getDataFn(),则可以发送请求。

原因如下:

someFetch.flush() 只会在 someFetch()执行的过程中去执行,单独执行someFetch.flush()是不会发送请求的,或许可以考虑改用以下这种写法

// 执行拿到数据函数
async function getDataFn(enforcement){
    if(enforcement){
        return ((await throttleFn()) && (await throttleFn.flush()))
    }

    return await throttleFn()
}

总结:在使用debounce 和 throttle 的时候使用flush()强制执行时,确保节流和防抖接受的函数正在执行过程中,flush()才会生效