Accumulate ids to make a single ajax request
I was able to somehow encapsulate the logic be creating a function generator that holds the previous two functions like this:



  const fakeData = [{
      id: 1,
      name: 'foo'
    },
    {
      id: 2,
      name: 'bar'
    },
    {
      id: 3,
      name: 'baz'
    }
  ];

  function makeGetter(fetchFunc, debounceTime = 400) {
    let idsToFetch = [];

    let getItemsPromise, resolve, reject;

    const fetchItems = _.debounce(() =&gt; {
      console.log('fetching items...');
      const currentResolve = resolve;
      const currentReject = reject;
      const currentIdsToFetch = idsToFetch;

      Promise.resolve(fetchFunc(currentIdsToFetch))
        .then(res =&gt; currentResolve(res))
        .catch(err =&gt; currentReject(err));

      getItemsPromise = resolve = reject = null;
      idsToFetch = [];
    }, debounceTime);

    const getItems = (ids) =&gt; {
      idsToFetch = ids.filter((id) =&gt; !idsToFetch.includes(id)).concat(idsToFetch);
      if (!getItemsPromise) {
        getItemsPromise = new Promise((_resolve, _reject) =&gt; {
          resolve = _resolve;
          reject = _reject;
        });
      }

      fetchItems();

      return getItemsPromise
        .then((res) =&gt; {
          return res.filter((item) =&gt; ids.includes(item.id));
        })
    }

    return getItems;
  }

  const getItems = makeGetter((ids) =&gt; {
    // simulating ajax request
    return new Promise((resolve, reject) =&gt; {
      setTimeout(function() {
        const result = ids.map((id) =&gt; fakeData.find(item =&gt; item.id == id));
        resolve(result);
      }, 400);
    })
  });


  setTimeout(() =&gt; {
    console.log('first request start');
    getItems([1]).then(res =&gt; console.log('first result:', res));
  }, 100);
  setTimeout(() =&gt; {
    console.log('second request start');
    getItems([1, 2]).then(res =&gt; console.log('second result:', res));
  }, 200)
  setTimeout(() =&gt; {
    console.log('third request start');
    getItems([1, 3]).then(res =&gt; console.log('third result:', res));
  }, 300)
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"&gt;&lt;/script&gt;