javascript – 使用promises实现的Debounce功能

前端之家收集整理的这篇文章主要介绍了javascript – 使用promises实现的Debounce功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试实现一个与 javascript中的promise一起使用的去抖函数.这样,每个调用者都可以使用Promise消耗“debounced”函数的结果.这是迄今为止我能想到的最好的:
function debounce(inner,ms = 0) {
  let timer = null;
  let promise = null;
  const events = new EventEmitter();  // do I really need this?

  return function (...args) {
    if (timer == null) {
      promise = new Promise(resolve => {
        events.once('done',resolve);
      });
    } else {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      events.emit('done',inner(...args));
      timer = null;
    },ms);

    return promise;
  };
}

理想情况下,我想实现这个实用程序函数而不引入依赖于EventEmitter(或实现我自己的基本版本的EventEmitter),但我想不出办法.有什么想法吗?

解决方法

我找到了一个更好的方法来实现承诺:
function debounce(inner,ms = 0) {
  let timer = null;
  let resolves = [];

  return function (...args) {    
    // Run the function after a certain amount of time
    clearTimeout(timer);
    timer = setTimeout(() => {
      // Get the result of the inner function,then apply it to the resolve function of
      // each promise that has been created since the last time the inner function was run
      let result = inner(...args);
      resolves.forEach(r => r(result));
      resolves = [];
    },ms);

    return new Promise(r => resolves.push(r));
  };
}

我仍然欢迎建议,但新的实现回答了我关于如何实现这个函数的原始问题,而不依赖于EventEmitter(或类似的东西).

原文链接:https://www.f2er.com/js/151188.html

猜你在找的JavaScript相关文章