async-deps

1.1.0 • Public • Published

async-props

Build Status Coverage Status

A javascript module to load and cache asynchronous dependencies.

Usage

const customerLoader = createLoader(
  (props) => props.customer,
  (id, next) => {
    console.log('Loading ...');
    fetchCustomer(id, (err, customer) => {
      if (err) return next(err);
      next(null, { customer });
    });
  }
);
 
const props = { customer: '1' };
customerLoader(props, (err, state) => {  // => "Loading ..."
  // ...
 
  loadSecondTime();
});
 
function loadSecondTime() {
  customerLoader(props, (err, state) => {
    // The asynchronous function to fetch the customer
    // isn't called again.  Instead the previous cached value
    // is used.  Therefore is `state` the same object as
    // before.
  });
}
 
function loadWithDifferentProps() {
  props.customer = '2';
  customerLoader(props, (err, state) => {  // => "Loading ..."
    // Since the id in the props changed, the function is
    // called again.
  });
}

Combine loaders

You can also combine loaders.

...
 
const customerLoader = createLoader(
  (props) => props.customer,
  (id, next) => {
    console.log('Loading ...');
    fetchCustomer(id, (err, customer) => {
      if (err) return next(err);
      next(null, { customer });
    });
  }
);
 
const postsLoader = createLoader(
  customerLoader,
  (customer, next) => {
    fetchPosts(customer.posts, next);
  }
);
 
...

Tests

$ npm test

Readme

Keywords

Package Sidebar

Install

npm i async-deps

Weekly Downloads

1

Version

1.1.0

License

ISC

Last publish

Collaborators

  • domachine