在項目的配置中,看到了一個請求,類似是這樣的
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()才會生效