npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

batching

v1.0.6

Published

Map multiple call async functions that have the same context with the earliest result returned.

Downloads

119

Readme

Batching

Map multiple call async functions that have the same context with the earliest result returned.

Usage

Assume you have a slow API

async function slowDoubleAPI(a) {
  console.log(`slowDoubleAPI(${a})`);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a !== 'number') {
        reject(new Error(`a param expect a number, but received ${a}`));
      }
      resolve(a * 2);

    }, _.random(500, 700));
  });
}

and make a batch call

async function testWithoutBatch() {
  try {
    let results = await Promise.all([
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(1),
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(3),
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(1),
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(1),
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(3),
      slowDoubleAPI(1),
      slowDoubleAPI(2),
      slowDoubleAPI(1),
    ]);
    console.log('RESULT : ', results);
  }
  catch (err) {
    console.log(`ERROR ${err.message}`);
  }
};

testWithoutBatch();

You realize that a lot of calls have the same context, and don't want to repeat it.

slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(1)
slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(3)
slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(1)
slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(1)
slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(3)
slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(1)
RESULT :  [ 2, 4, 2, 2, 4, 6, 2, 4, 2, 2, 4, 2, 2, 4, 6, 2, 4, 2 ]

Let batch them ...

const batch = require('batching');

async function testWithBatch() {
  try {
    let results = await Promise.all([
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [3]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [3]),
      batch(slowDoubleAPI, [1]),
      batch(slowDoubleAPI, [2]),
      batch(slowDoubleAPI, [1]),
    ]);
    console.log('RESULT : ', results);
  }
  catch (err) {
    console.log(`ERROR ${err.message}`);
  }
};

testWithBatch();

The first call slowDoubleAPI(1) will be executed, but later call slowDoubleAPI(1) before first call finish won't, just push to queue, and assign them to the first call result when it finishes.

slowDoubleAPI(1)
slowDoubleAPI(2)
slowDoubleAPI(3)
RESULT :  [ 2, 4, 2, 2, 4, 6, 2, 4, 2, 2, 4, 2, 2, 4, 6, 2, 4, 2 ]

Let turn on log to view detail :

batch.setLog(true);

Will print :

[batch] slowDoubleAPI() start, with :
 * ARGS        :  [1]
 * THIS        :  undefined

slowDoubleAPI(1)
[batch] slowDoubleAPI() start, with :
 * ARGS        :  [2]
 * THIS        :  undefined

slowDoubleAPI(2)
[batch] slowDoubleAPI() start, with :
 * ARGS        :  [3]
 * THIS        :  undefined

slowDoubleAPI(3)
[batch] slowDoubleAPI() finish successful, with :
 * TIME        :  601ms
 * ARGS        :  [3]
 * THIS        :  undefined
 * Callbacks   :  2
 * RESULT      :  6

[batch] slowDoubleAPI() finish successful, with :
 * TIME        :  644ms
 * ARGS        :  [1]
 * THIS        :  undefined
 * Callbacks   :  10
 * RESULT      :  2

[batch] slowDoubleAPI() finish successful, with :
 * TIME        :  676ms
 * ARGS        :  [2]
 * THIS        :  undefined
 * Callbacks   :  6
 * RESULT      :  4

API

Batch(options) ⇒ function

Create new batch

Kind: global function
Returns: function - batch

| Param | Type | Default | Description | | --- | --- | --- | --- | | options | object | | | | [options.logStart] | boolean | function | false | interface : (asyncFunc : function, context : object) => void | | [options.logFinish] | boolean | function | false | interface : (asyncFunc : function, context : object, err : object, res : any) => void | | [options.isArgsEqual] | function | .isEqual | arguments comparator | | [options.isThisEqual] | function | .isEqual | this pointer comparator |

Example

const { Batch } = require('batching');

const custom_batch = Batch({
  isArgsEqual : (a, b) => a[0] === b[0],
  isThisEqual : (a, b) => a === b,
  logFinish   : true
});


Batch~wrap(asyncFunc, [thisArg]) ⇒ function

Wrap a async function to support batching

Kind: inner method of Batch
Returns: function - batchedAsyncFunction : (...args) => Promise

| Param | Type | | --- | --- | | asyncFunc | function | | [thisArg] | any |

Example

// Instead of : 
const batch = require('batching');

let user1 = await batch(findOne, { id : 10000 }, UserModel);
let user2 = await batch(findOne, { id : 10001 }, UserModel);
let user3 = await batch(findOne, { id : 10000 }, UserModel);

// Use can wrap findOne() :

const batchedFindOne = batch.wrap(findOne, UserModel);

// And call it :

let user1 = await batchedFindOne({ id : 1000 });
let user2 = await batchedFindOne({ id : 1001 });
let user3 = await batchedFindOne({ id : 1000 });


Batch~batch(asyncFunc, args, thisArg) ⇒ Promise

Map multiple call async functions that have the same context with the earliest result returned.

Kind: inner method of Batch
Returns: Promise - that return by first finished invoking

| Param | Type | | --- | --- | | asyncFunc | function | | args | array | | thisArg | object |

Example

const batch = require('batching');

let store = await batch(findOneStore, [{ id : 10010 }]);

// with thisArg
let store = await batch(findOne, [{ id : 10010 }], StoreModel);


Batch~setLog(options)

Set log options

Kind: inner method of Batch

| Param | Type | Description | | --- | --- | --- | | options | boolean | object | turn log on or off, or customer log function |

Example

// set all log
batch.setLog(true);

// set specific log
batch.setLog({
  logStart : false,
  logEnd   : true,
});

// custom log function
batch.setLog({
  logStart : (asyncFunc, context) => {},
  logEnd   : (asyncFunc, context, err, res) => {},
});