1.1.0 • Published 8 years ago
async-deps v1.1.0
async-props
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