Igino Boffa
Igino Boffa

Reputation: 736

Debounce and return

I'm having an issue with this piece of code:

function aFunction(){
  ....
    var deferred = $q.defer();
    debounce(function () {
       deferred.resolve(service.subscribe0(data));
    }, 350);
  return deferred.promise;
}

The returned promise is never resolved. Debounce function is a 3rd party function with a lot of downloads from NPM, so I can be sure it works.

Can it be because the return statement "removes" the scope of the function? How can I avoid this and resolve the promise?

Upvotes: 0

Views: 3409

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

You misunderstand what debounce() does.

debounce() is a function that accepts a function, and returns a function. The returned function will only call the passed callback after N milliseconds of silence (that is, if you call the debounced function very quickly in sequence, only the last call will take effect, after the time elapses).

debounce() itself doesn't call the function you pass it. So, deferred.resolve() never gets called.

Upvotes: 7

Shilly
Shilly

Reputation: 8589

I would expect something like:

const getData = data => Promise.resolve( service.subscribe0( data ));
grid.addEventListener( 'scroll', debounce( getData, 350 ));

We want the grid to update itsself on scroll, but debounce it so it won't flood the service with calls. So we have to debounce the function tied to the scrolling instead of the data call, since there's no link between two different data calls.

Upvotes: 0

Related Questions