累积 ID 以发出单个 ajax 请求

Accumulate ids to make a single ajax request

我有多个地方需要发出 ajax 请求来获取与某些 ID 对应的项目。但是,我只想通过累积这些 id 并消除发出 ajax 请求的实际方法来发出单个请求...到目前为止,我已经想出了这段代码,但感觉 ugly/non-reusable.

是否有任何 simpler/recommended 方法可以在不共享 resolve/promise 变量的情况下实现类似的结果?

这是一个fiddle

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

let idsToFetch = [];

let getItemsPromise, resolve, reject;

const fetchItems = _.debounce(() => {
  console.log('fetching items...');
  const currentResolve = resolve;
  const currentReject = reject;

  // simulating ajax request
  setTimeout(function() {
    const result = idsToFetch.map((id) => fakeData.find(item => item.id == id));
    currentResolve(result);
  }, 400);

  getItemsPromise = resolve = reject = null;
}, 500);

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

  fetchItems();

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

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

我能够通过创建一个包含前两个函数的函数生成器以某种方式封装逻辑,如下所示:

   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(() => {
      console.log('fetching items...');
      const currentResolve = resolve;
      const currentReject = reject;
      const currentIdsToFetch = idsToFetch;

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

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

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

      return currentPromise
        .then((res) => {
          return res.filter((item) => ids.includes(item.id));
        })
    }

    return getItems;
  }

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


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

我发现编写一个行为完全在我控制之下的 debounce() 函数比依赖库方法更简单。

特别是,我特意设计了一种与问题中不同的去抖动行为,通过这种行为(如果我理解正确的话)第一个,可能 ,快速序列的请求必须等待去抖动延迟到期。

在下面的代码中,使用 debouncePromise 代替原来的 getItemsPromise 来表示去抖动期,在此期间禁止抓取并允许累积请求数据。从静止状态(每当 debouncePromise === null 时),下一个 fetch() 调用将尽快获取数据(下一个滴答)。只有第二次和后续调用被去抖动,直到去抖动期结束并且 debounce() 实例 returns 进入其静止状态。我认为这是与原始范例一样有效的 "debounce" 范例,而且可以说更好。 (如果不是,则可以稍微修改 fetch() 以提供原始行为)。

除此之外,差异很小:

  • 避免凌乱的外化 resolvereject
  • 为了保持 debounce() 的通用性,除了 fetcherdelay.
  • 之外,还传递了 resultsFilter 函数

代码中的进一步注释。

function debounce(fetcher, resultsFilter, delay) {
    let idsToFetch = [],
        debouncePromise = null;
    function reset() { // utility funtion - keeps code below clean and DRY
        let idsToFetch_ = idsToFetch;
        idsToFetch = [];
        return idsToFetch_;
    }
    function fetch(ids) {
        idsToFetch = idsToFetch.concat(ids.filter(id => !idsToFetch.includes(id))); // swapped around so as not to reverse the order.
        if (!debouncePromise) {
            // set up the debounce period, and what is to happen when it expires.
            debouncePromise = new Promise(resolve => {
                setTimeout(resolve, delay);
            }).then(() => {
                // on expiry of the debounce period ...
                debouncePromise = null; // ... return to quiescent state.
                return fetcher(reset()); // ... fetch (and deliver) data for all request data accumulated in the debounce period.
            });
            // *** First call of this debounce period - FETCH IMMEDIATELY ***
            return Promise.resolve(reset()).then(fetcher); // (1) ensure fetcher is called asynchronously (as above). (2) resultsFilter is not necessary here.
        } else {
            return debouncePromise.then(res => resultsFilter(ids, res)); // when debouncePromise exists, return it with chained filter to give only the results for these ids.
        }
    }
    return fetch;
}

示例用法:

function fetchItems(ids) {
    const fakeData = [
        { 'id': 1, 'name': 'foo' },
        { 'id': 2, 'name': 'bar' },
        { 'id': 3, 'name': 'baz' },
        { 'id': 4, 'name': 'zaz' }
    ];
    if (ids.length > 0) {
        return new Promise(resolve => { // simulate ajax request
            setTimeout(resolve, 400);
        }).then(() => {
            return ids.map(id => fakeData.find(item => item.id == id));
        });
    } else {
        return Promise.resolve([]);
    }
}
function filterResults(ids, results) {
    return results.filter(item => ids.includes(item.id));
}

// ******************************************************
let getItems = debounce(fetchItems, filterResults, 500);
// ******************************************************

setTimeout(() => {
    console.log('first request start');
    getItems([1]).then(res => console.log('first result:', res));
}, 100);
setTimeout(() => {
    console.log('second request start');
    getItems([1, 2]).then(res => console.log('second result:', res));
}, 200);
setTimeout(() => {
    console.log('third request start');
    getItems([1, 3]).then(res => console.log('third result:', res));
}, 300);
setTimeout(() => {
    console.log('fourth request start');
    getItems([1, 4]).then(res => console.log('fourth result:', res));
}, 2000);

Tested to the extent of this fiddle