My implementation of debounce axios request left the promise in pending state forever, is there a better way?

前端 未结 2 1914
悲&欢浪女
悲&欢浪女 2021-01-18 08:53

I need a simple debounce function with immediate always true.
Without resorting to lodash and with the help of Can someone explain the "debounce" function in J

2条回答
  •  无人共我
    2021-01-18 09:20

    In essence, you need to share result of your debounce function. In your case, thats a promise:

    const debouncedGetData = debounce(getData, 500)
    let promiseCount = 0
    let resultCount = 0
    test()
    
    function test() {
      console.log('start')
      callDebouncedThreeTimes()
      setTimeout(callDebouncedThreeTimes, 200)
      setTimeout(callDebouncedThreeTimes, 900)
    }
    
    function callDebouncedThreeTimes () {
       for (let i=0; i<3; i++) {
          debouncedGetData().then(r => {
            console.log('Result count:', ++resultCount)
            console.log('r', r)
          })
       }
    }
    
    function debounce(func, wait) {
        let waiting;
        let sharedResult;
        return function() {
            // first call will create the promise|value here
            if (!waiting) {
              setTimeout(clearWait, wait)
              waiting = true
              sharedResult = func.apply(this, arguments);
            }
            // else new calls within waitTime will be discarded but shared the result from first call
    
            function clearWait() {
              waiting = null
              sharedResult = null
            }
    
            return sharedResult
        };
    }
    
    function getData () {
      console.log('Promise count:', ++promiseCount)
      return new Promise((resolve, reject) => {
        setTimeout(() => {
           resolve(666)
        }, 1000)
      })
    }
    

提交回复
热议问题