The AsyncCallReducer
is a function to reduce calls using browser storage. A Promise can be encapsulated, a single HTTP request will be triggered regardless of the number of calls. Concurrent calls are added on a queue and return's data are stored in the browser.
Rules:
- The first call is granted
- Concurrent calls are blocked and added on a queue, then execute when the first call is ready
- Next calls get the data from the browser storage
The function is available as the async-call-reducer
package name on npm and Github.
npm i --save-dev async-call-reducer
yarn add --dev async-call-reducer
AsyncCallReducer
was built for Node.js >=12
.
The project includes an example of an implementation of AsyncCallReducer
in the directory ./demo/
.
Imagine the following function to get data from an API. Each call will trigger an HTTP request.
async function getData() {
const data = await fetch('https://swapi.dev/api/people/?page=1');
return await data.json();
}
By wrapping the function with the AsyncCallReducer
, a single HTTP request will be triggered. Other calls will return exactly the same value, either from the storage or from the queue if the calls was concurrent.
async function getData() {
+ return await asyncCallReducer({
+ key: 'swapi',
+ callback: async () => {
const data = await fetch('https://swapi.dev/api/people/?page=1');
return await data.json();
+ }
+ });
}
string = asyncCallReducer
Tells to the function the storage key used as a prefix. Following keys will be created:
asyncCallReducerData
: Stored dataasyncCallReducerLoading
: Blocker for concurrent calls
asyncCallReducer({
key: 'swapi'
});
string = sessionStorage
Tells to the function which browser storage method to use (sessionStorage|localStorage
).
asyncCallReducer({
storage: 'localStorage'
});
Promise
Tells the function the promise to be executed.
💡 Keep the
async
keyword, thecallback
function must returns a Promise.
asyncCallReducer({
callback: async () => {
// Request data from an API and return data here
}
});
AsyncCallReducer
is licensed under the MIT License.
Created with ♥ by @yoriiis.