使用 promise 实现的去抖动功能 [英] Debounce function implemented with promises

查看:17
本文介绍了使用 promise 实现的去抖动功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个与 javascript 中的 promise 一起使用的 debounce 函数.这样,每个调用者都可以使用 Promise 来使用去抖动"函数的结果.这是迄今为止我能想到的最好的:

I'm trying to implement a debounce function that works with a promise in javascript. That way, each caller can consume the result of the "debounced" function using a Promise. Here is the best I have been able to come up with so far:

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 基本版本)的情况下实现这个实用程序函数,但我想不出办法来做到这一点.有什么想法吗?

Ideally, I would like to implement this utility function without introducing a dependency on EventEmitter (or implementing my own basic version of EventEmitter), but I can't think of a way to do it. Any thoughts?

推荐答案

我找到了一个更好的方法来实现这个承诺:

I found a better way to implement this with promises:

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(或类似的东西)的情况下实现此功能.

I still welcome suggestions, but the new implementation answers my original question about how to implement this function without a dependency on EventEmitter (or something like it).

这篇关于使用 promise 实现的去抖动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆