累积id以发出单个ajax请求

时间:2018-05-07 01:06:31

标签: javascript ajax promise debounce

我有多个地方需要制作ajax请求来获取与某些ID相对应的项目。但是,我只想通过累积这些ID并去掉制作ajax请求的实际方法来做出一个请求......到目前为止,我已经提出了这个代码,但它只是觉得丑陋/不可重用。

有没有更简单/推荐的方法来实现类似的结果,而不像我在这里那样共享[...menu] / resolve变量?

这是fiddle

promise
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)

2 个答案:

答案 0 :(得分:1)

我发现编写一个完全由我控制的行为的debounce()函数更简单,而不是依赖于库方法。

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

在下面的代码中,代替原始getItemsPromisedebouncePromise用于表示去抖期,在此期间取消取消并允许请求数据累积。从静止状态(只要debouncePromise === null),下一个fetch()调用将尽快获取数据(下一个勾号)。只有第二次和后续的呼叫被去抖动,直到去抖期到期并且debounce()实例返回其静止状态。我认为这与原始的“辩护”范式一样有效,可以说更好。 (如果没有,则可以轻微修改fetch()以提供原始行为)。

除此之外,差异很小:

  • 凌乱的外化resolvereject可以避免
  • 为了保持debounce()通用,除了resultsFilterfetcher之外,还会传递delay函数。

代码中的进一步评论。

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

答案 1 :(得分:0)

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

&#13;
&#13;
   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)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
&#13;
&#13;
&#13;