title: My implementation of debounce axios request left the promise in pending state forever, is there a better way?
body: <p>I need a simple debounce function with immediate always true.<br>
  Without resorting to lodash and with the help of <a href="https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript">Can someone explain the &quot;debounce&quot; function in Javascript</a> , I implemented it as following,</p>
  
  <pre><code>function debounce(func, wait) {
      var timeout;
      return function() {
          if (!timeout) func.apply(this, arguments);
          clearTimeout(timeout);
          timeout = setTimeout(()=&gt;{timeout = null}, wait);
      };
  };
  </code></pre>
  
  <p>It works as expected until I need to debounce axios request. Assumed I have a debounced axios method, I would like the calling method to be as usual, which means my debounced axios method should return promise I believe.</p>
  
  <pre><code>   //the calling method should not change   
     debounced_axios().then(res =&gt; {...}).catch(err =&gt; {...}) 
  </code></pre>
  
  <p>The essence of original debounce implementation is to just run func <strong>once</strong> in a wait timeframe, but how do I just return <strong>one</strong> promise in a wait timeframe ?</p>
  
  <p>Then I came up with the following solution</p>
  
  <pre><code>all_timers = {}
  function debounce_axios(input, wait) {
      return new Promise((resolve, reject) =&gt; {
          let timer = all_timers.[input] //check if it is a repeated request, pseudo code
          if (!timer) {
              axios(input).then(res=&gt;{
                  resolve(res)
              }).catch(err =&gt; {
                  reject(err)
              })
          }
          clearTimeout(timer);
          timer = setTimeout(()=&gt;{timer = null}, wait);
          all_timers[input] = timer
      };
  };
  </code></pre>
  
  <p>So the essence of my debounce_axios is to let the promise stay in pending state for the repeated request.Then the calling method <code>debounced_axios().then(res =&gt; {...}).catch(err =&gt; {...})</code> does not need to change.</p>
  
  <p>The answer here <a href="https://stackoverflow.com/questions/38286358/are-javascript-forever-pending-promises-bad">Are JavaScript forever-pending promises bad?</a> said "There should be no side effect."</p>
  
  <p>But I am still not 100% sure about letting a promise stay in pending forever. </p>
  
  <p>The other question is that <a href="https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns" rel="noreferrer">Promise Anti patterns</a> suggested not creating unnecessary promise. But in my case creating a new promise seems necessary.</p>
  
  <p>In a nutshell is there a simple to way to debounce axios request (or any request returns promise) ? </p>