Coder Social home page Coder Social logo

debounce-async's Introduction

debounce-async

Build Status NPM Package Dependency status devDependency status

NPM

A debounced function that delays invoking asynchronous functions.

Preliminaries

A debounced function groups sequential calls to a function within a period. Only the last call in the group is executed. The others are simply ignored with rejections as if no calls to them ever happened.

Say d is a debounced function of f, var d = debounce(f, 1000);, where f is an asynchronous function that returns a promise being resolved in 400ms since it gets called. Below is a depiction of a sequence of calls to d.

seconds elapsed    0         1         2         3         4
d called           - d d d d d - - - - - d d d d - - d - - - - -
                     x x x x |           x x x x     |
f called                     +-------> f             +-------> f
                                       |                       |
promise resolved                       +-> *                   +-> *

d denotes a call to function d, f denotes a call to function f, and * denotes a promise returned by f is resolved. x denotes a call to d returns a rejected promise.

Installation

npm install debounce-async --save

Usage

var debounce = require( 'debounce-async' );

/**
  * debounce(func, [wait=0], [options={}])
  *
  * @param {Function} func The function to debounce.
  * @param {number} [wait=0] The number of milliseconds to delay.
  * @param {Object} [options={}] The options object.
  * @param {boolean} [options.leading=false] Specify invoking on the leading edge of the timeout.
  * @param {cancelObj} [options.cancelObj='canceled'] Specify the error object to be rejected.
  * @returns {Function} Returns the new debounced function.
  */

This package aims at maintaining the same signature of the debounce function from lodash. Please report if there is discrenency.

Example

Promise

var debounce = require( 'debounce-async' );

var f = value => new Promise( resolve => setTimeout( () => resolve( value ), 50 ) );
var debounced = debounce( f, 100 );

var promises = [ 'foo', 'bar' ].map( debounced );
promises.forEach( promise => {
  promise
    .then( res => console.log( 'resolved:', res ) )
    .catch( err => console.log( 'rejected:', err ) )
});

// Output:
// rejected: canceled
// resolved: bar

In the example above, f is an asynchronous function which returns a promise. The promise is resolved with the input after 50ms. debounced is a debounced function of f with a delay of 100ms.

The debounced function is called twice consecutively by the callback of Array.proptotype.map, with 'foo' and 'bar' being the input value respectively. The two returned promises are next fullfilled by printing the resolved result or rejected error on the console.

This snippet results in the given output. The first promise was rejected while the second one was resolved. It is because the second call comes before the delay of 100ms since the first call fired.

async/await

Same thing when it comes to asynchronous ES7 async/await functions. Take the prior example and transform the f into an ES7 async function.

var f = async value => await new Promise( resolve => setTimeout( () => resolve( value ), 50 ) );

Same output can be expected.

Test

npm test

License

MIT. See LICENSE.md for details.

debounce-async's People

Contributors

szchenghuang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

debounce-async's Issues

Function is exported incorrectly

The actual function is exported to exports.default.
What this means is that when trying to "require" debounce, one has to either do

const {default: debounce} = require("debounce-async")

or

const debounce = require("debounce-async").default

Leading edge debounce doesn't work consistently

When configuring this library to use a leading edge debounce, things don't work consistently.

On each consecutive call the debounce is applied in an alternating leading, then trailing, then leading fashion.

That seems to be because invokeAtLeading never clears the latestResolve variable upon resolution:

function invokeAtLeading( args, resolve, reject ) {
func.apply( this, args ).then( resolve ).catch( reject )
shouldCancel = false
}

On every other call this condition is failing because latestResolve is still set:

if ( !latestResolve ) { // The first call since last invocation.

And the execution falls through to invokeAtTrailing even when latestResolve has long since been resolved.

Throws error when cancelled

This lib is useful, but it throws a "cancelled" error when a debounced function is called multiple times. To work with node/browser promises, I would then need to "catch" this cancelled error..but in reality it should only throw if the promise returned by the debounced function throws.

debounce(() => {
    return new Promise((resolve, reject) => {
        // some logic here...
        resolve(); // should never throw an error

        // some more logic
        reject('Error message'); // this should throw
    });
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.