async-data-cache
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

async-data-cache

A simple async data cache with no dependencies.

This library allows your to cache the result of an async call.

It's useful when you have to call an api or execute a heavy query and the performance are more important than the real-time. You can easily choose the cache time to live (ttl).

Installation

yarn add async-data-cache

Usage

// Simulate a function that requires 3 secs to complete (e.g. a heavy db query)
const dataFetcher = (): Promise<Array<number>> => {
  console.log('dataFetcher');
  return new Promise((res, rej) => {
    setTimeout(() => res([1, 2, 3, 4, 5]), 3000);
  })
}

(async () => {
  // With the cache the dataFetcher function will be called only 1 time.
  const cache = new DataCache<Array<number>>(dataFetcher);
  let data = await cache.getData();
  console.log(data);
  data = await cache.getData();
  console.log(data);
  data = await cache.getData();
  console.log(data);
  data = await cache.getData();
  console.log(data);
})();

To change the ttl, pass the ttl minutes to the DataCache constructor

// 1 hour of ttl
const cache = new DataCache<Array<number>>(dataFetcher, 60);

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.7
    0
    • latest

Version History

Package Sidebar

Install

npm i async-data-cache

Weekly Downloads

1

Version

1.0.7

License

MIT

Unpacked Size

6.25 kB

Total Files

8

Last publish

Collaborators

  • emiliosp